CTRL + K
CTRL + K
0. Int roduct ion t o Dat a St ruct ures & Algorit hms wit h Leet code
1. Dut ch Flags Problem
2. List Part it oning
3. Count ers
4. Majorit y Vot e
5. Removing Parent heses
6. Remove Duplicat es from Sort ed Array
7. Mat hs
8. Lone Int eger
9. Pigeonhole
10. Check If N and It s Double Exist
11. Find Numbers wit h Even Number of Digit s
12. Two Point ers
13. Remove Element
14. Replace Element s wit h Great est Element on Right Side
15. Valid Mount ain Array
16. Sort Array by Parit y
17. Squares of a Sort ed Array
18. Max Consecut ive Ones
19. Sliding Window
20. Max Consecut ive Ones 3
21. St acks
22. Balanced Bracket s
23. General St rings & Arrays
24. Move Zeros
25. Unique Element s
26. Merge Sort ed Array
27. Mat rices
28. Valid Square
29. Mat rix Search Sequel
30. Unt it led
31. Int roduct ion
32. Backt racking
33. Permut at ions
34. Int roduct ion
35. Minimum (Maximum) Pat h t o Reach a Target
36. Min Cost Climbing St airs
37. Coin Change
38. Minimum Pat h Sum
39. Triangle
40. Minimum Cost t o Move Chips t o The Same Posit ion
41. Consecut ive Charact ers
42. Perfect Squares
43. Dist inct Ways
44. Climbing St airs
45. Unique Pat hs
46. Number of Dice Rolls wit h Target Sum
47. Merging Int ervals
48. Minimum Cost Tree From Leaf Values
49. DP on St rings
50. Levensht ein Dist ance
51. Longest Common Subsequence
52. Int roduct ion
53. First Bad Version
54. Sqrt (x)
55. Search Insert Posit ion
56. Advanced
57. KoKo Eat ing Banana
58. Capacit y t o Ship Packages wit hin D Days
59. Minimum Number of Days t o Make m Bouquet s
60. Split array largest sum
61. Minimum Number of Days t o Make m Bouquet s
62. Koko Eat ing Bananas
63. Find K-t h Smallest Pair Dist ance
64. Ugly Number 3
65. Find t he Smallest Divisor Given a Threshold
66. Kt h smallest number in mult iplicat ion t able
67. Binary Trees
68. Merging Binary Trees
69. Binary Tree Preorder Traversal
70. Binary Tree Post order Traversal
71. Binary Tree Level Order Traversal
72. Binary Tree Inorder Traversal
73. Symmet ric Tree
74. Populat ing Next Right Point ers in Each Node
75. Populat ing Next Right Point ers in Each Node II
76. 106. Const ruct Binary Tree from Inorder and Post order Traversal
77. Serialise and Deserialise a Linked List
78. Maximum Dept h of Binary Tree
79. Lowest Common Ancest or of a Binary Tree
80. n-ary Trees
81. Unt it led
82. Minimum Height Trees
83. Binary Search Trees
84. Count ing Maximal Value Root s in Binary Tree
85. Count BST nodes in a range
86. Invert a Binary Tree
87. Maximum Difference Bet ween Node and Ancest or
88. Binary Tree Tilt
89. Pract ice
90. What is a Linked List ?
91. Add Two Numbers
92. Add Two Numbers 2
93. Reverse a Linked List
94. Tort oise & Hare Algorit hm
95. Middle of t he Linked List
96. Int roduct ion
97. Uncomplet ed
98. Minimum Cost For Ticket s
99. Minimum Falling Pat h Sum
Introduction to Data Structures
& Algorithms with Leetcode
You can read this here ht t ps://beesec.git book.io/algorit hms/
Int roduct ion t o Dat a St ruct ures & Algorit hms wit h Leet code
Algorithms
Welcome t o Bee's guide t o dat ast ruct ures and algorit hms! This is based on
ht t ps://git hub.com/guyinat uxedo/night mare
• Learn dat a st ruct ures & algorit hms (DS&A) using leet code
• Sort ed by how likely it is t o show up in an int erview and how vit al t hat knowledge is t o
underst anding ot her DS&A.
• The problems are most ly medium - hards, I t ry t o not include easy problems unless t hey are t he
first problem in a cat egory.
This is a course on dat ast ruct ures and algorit hms based around leet code problems. Learn DS&A via
problems, wit h lengt hy explanat ions.
This guide is ordered by how likely it is for t hat dat ast ruct ure / algorit hm t o show up in an int erview
and how vit al t hat knowledge is t o underst anding ot her dat a st ruct ures / algorit hms.
Each sect ion will lead wit h a leet code st yle problem, and end wit h problems you can do on your own.
This way, you only ever learn what is relevant .
All code will be in Pyt hon due t o how easy it is t o read. If you want t o cont ribut e more code, feel free
t o. This is on Git Hub aft er all!
If you're okay wit h Pyt hon, but want t o learn t he advanced st uff check out my ot her book
ht t ps://git hub.com/bee-san/Pyt hon-Zero-t o-Hero
I also have my own blog, ht t ps://skerrit t .blog t hat you may enjoy.
Resources
You should roughly know t hese t hings. I have linked t o some of my own resources for you t o learn t hem:
• Pyt hon (Not an expert , you can use ot her languages or cont ribut e more languages)
• CTCI
• MIT 6.006
How to contribute
• Explain t hings more easily
• Look t hrough my Not Done Yet sect ion and complet e / improve t hem!
2. Leet code discussion board is popping, and t here's many Yout ube videos about each plat form
3. AlgoExpert is not paying me t o t ell you t hat t he scariest t hing in t he world is not knowing how t o
invert a binary t ree in a coding int erview yet.
6. Honest ly if any ot her coding company came along and paid me t o advert ise t heir product I would
it 's just I used Leet code. Deciding on what the best platform to use is another form of
procrastination. I just picked t he first one I saw and went wit h it .
Important Notes
• Not all solut ions are made by me (bee-san). This book is 100% open source and somet imes people
on Leet code forums have way bet t t er solut ions t han I do.
Next
Dut ch Flags Problem
Last updat ed 4 years ago
The Dutch national flag problem [1] is a comput er science programming problem proposed by Edsger
Dijkst ra.[2] The flag of t he Net herlands consist s of t hree colors: red, whit e and blue. Given balls of
t hese t hree colors arranged randomly in a line (it does not mat t er how many balls t here are), t he t ask is
t o arrange t hem such t hat all balls of t he same color are t oget her and t heir collect ive color groups are
in t he correct order.
The solut ion t o t his problem is of int erest for designing sort ing algorit hms; in part icular, variant s of t he
quicksort algorit hm t hat must be robust t o repeat ed element s may use a t hree-way part it ioning
funct ion t hat groups it ems less t han a given key (red), equal t o t he key (whit e) and great er t han t he key
(blue). Several solut ions exist t hat have varying performance charact erist ics, t ailored t o sort ing arrays
wit h eit her small or large numbers of repeat ed element s
Previous
Next
Int roduct ion t o Dat a St ruct ures &
List Part it oning
Algorit hms wit h Leet code
Question Answer
Given a list of st rings strs , cont aining t he st rings "red" , "green" and "blue" , part it ion t he
list so t hat t he red come before green, which come before blue.
Constraints
Bonus: Can you do it in \mat hcal{O}(1)O(1) space? That is, can you do it by only rearranging t he list
(i.e. wit hout creat ing any new st rings)?
Example 1
Input
Output
Previous Next
Dut ch Flags Problem Count ers
counter = 0
for i in n: # n is a list of items
if condition(i):
counter += 1
else:
counter -= 1
counter = 0
while counter < len(s):
if condition(s[counter]):
counter += 1
Previous Next
List Part it oning Majorit y Vot e
Question Answer
Given an array of size n, find t he majorit y element . The majorit y element is t he element t hat
appears more than ⌊ n/2 ⌋ t imes.
You may assume t hat t he array is non-empt y and t he majorit y element always exist in t he array.
Example 1:
Input: [3,2,3]
Output: 3
Previous Next
Count ers Removing Parent heses
I know it 's not Leet code please don't kill me. I was in a compet it ion and I t hought t his was
neat . Couldn't find t he leet code alt ernat ive.
Question Answer
Given a st ring of parent heses s , ret urn t he minimum number of parent heses t o be removed t o
make t he st ring valid (i.e. each open parent hesis is event ually closed).
For example, given t he st ring "()())()" , you should ret urn 1. Given t he st ring ")(" , you should
ret urn 2, since we must remove all of t hem.
Previous Next
Majorit y Vot e Remove Duplicat es from Sort ed Array
If a quest ion ment ions a specific propert y about t he input dat a, oft en t he opt imal solut ion will make
use of t his propert y.
In t his case, we are t old t hat t he array is sort ed. That means our opt imal solut ion must make use of t he
fact it is sort ed.
List en carefully t o what your int erviewer is t elling you, every word might come in handy.
Question Answer
Given a sort ed array nums, remove t he duplicat es in-place such t hat each element appears only
once and ret urns t he new lengt h.
Do not allocat e ext ra space for anot her array, you must do t his by modifying the input array in-
place wit h O(1) ext ra memory.
Previous Next
Removing Parent heses Mat hs
Previous Next
Remove Duplicat es from Sort ed Array Lone Int eger
Question Answer
You are given a list of int egers nums where each int eger occurs exact ly t hree t imes except for
one which occurs once. Ret urn t he lone int eger.
Constraints
Example 1
Input
nums = [2, 2, 2, 9, 5, 5, 5]
Previous Next
Mat hs Pigeonhole
Question Answer
You are given a list nums of lengt h n + 1 picked from t he range 1, 2, ..., n . By t he
pigeonhole principle, t here must be a duplicat e. Find and ret urn it . There is guarant eed t o be
exact ly one duplicat e.
Bonus: Can you do t his in linear t ime and const ant space?
Previous Next
Lone Int eger Check If N and It s Double Exist
Question Answer
Given an array arr of int egers, check if t here exist s t wo int egers N and M such t hat N is
t he double of M ( i.e. N = 2 * M ).
• i != j
• arr[i] == 2 * arr[j]
Example 1:
Next
Previous
Find Numbers wit h Even Number
Pigeonhole
of Digit s
Modulus
To find out whet her a number is even or not , we use t he modulus operat or. Y % X implies t hat Y is
divided by X, and what ever t he remainder is will be t he result .
6 % 2 == 0 # False
The number being divided is called t he dividend, and t he number t hat divides t he dividend is called t he
divisor.
We can also use modulus for ot her t hings, such as checking if a number is odd. Or t urning a list int o a
loop. If we have a list t hat is size 6, and we want t o it erat e 9 numbers but have it loop back around, we
can use modulus for t his.
Question Answer
Given an array nums of int egers, ret urn how many of t hem cont ain an even number of digit s.
Previous Next
Check If N and It s Double Exist Two Point ers
Last updat ed 4 years ago
Two Pointers
Replace Element s wit h Great est
Remove Element
Element on Right Side
Previous
Next
Find Numbers wit h Even Number
Remove Element
of Digit s
Question Answer
Given an array nums and a value val, remove all inst ances of t hat value in-place and ret urn t he new
lengt h.
Do not allocat e ext ra space for anot her array, you must do t his by modifying the input array in-
place wit h O(1) ext ra memory.
The order of element s can be changed. It doesn't mat t er what you leave beyond t he new lengt h.
Clarification:
Confused why t he ret urned value is an int eger but your answer is an array?
Not e t hat t he input array is passed in by reference, which means a modificat ion t o t he input array
will be known t o t he caller as well.
Next
Previous
Replace Element s wit h Great est Element
Two Point ers
on Right Side
Question Answer
Given an array arr , replace every element in t hat array wit h t he great est element among t he
element s t o it s right , and replace t he last element wit h -1 .
Example 1:
Previous Next
Remove Element Valid Mount ain Array
Question Answer
Given an array of int egers arr , ret urn true if and only if it is a valid mountain array.
• arr.length >= 3
Example 1:
Previous
Replace Element s wit h Great est Element Next
Question Answer
Given an array A of non-negat ive int egers, ret urn an array consist ing of all t he even element s of
A , followed by all t he odd element s of A .
You may ret urn any answer array t hat sat isfies t his condit ion.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Previous Next
Valid Mount ain Array Squares of a Sort ed Array
2 Pointers
The 2 point ers t echnique is where we have 2 variables point ing at different part s of t he array. An
example is:
x = [1, 2, 3, 4, 5]
pointer1 = 0
pointer2 = len(x) - 1
while pointer1 <= pointer2:
print(pointer1 + pointer2)
pointer1 += 1
pointer2 -= 1
This code adds t he largest element t o t he smallest element and goes inwards int o t he code.
Very oft en we'll want 2, 3, 4 point ers in our array. These point ers do not always have t o move at t he
same speed. Having 2 point ers is oft en an evolut ion of using 2 for loops. Look at t his problem:
Given an array of sort ed numbers and a t arget sum, find a pair in t he array whose sum is equal t o t he
given t arget .
Given t he array is sort ed, our first t hought might be 2 nest ed for loops. This is O(n^2). We want O(n).
x = [1, 2, 3, 4, 5]
pointer1 = 0
pointer2 = len(x) - 1
target = 7
1 + 5 = 6
6 < target (7)
We know t he value is larger, so we move one t o t he right .
x = [1, 2, 3, 4, 5]
pointer1 = 2 # value 1
pointer2 = 4 # value 5
sum = 7
sum == target
The point ers pat t ern is an essent ial pat t ern for array manipulat ion, and we will see it come up a lot .
Especially wit h 2 point ers moving at different speeds.
Question Answer
Given an array of int egers A sort ed in non-decreasing order, ret urn an array of t he squares of
each number, also in sort ed non-decreasing order.
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Previous Next
Sort Array by Parit y Max Consecut ive Ones
Question Answer
Given a binary array, find t he maximum number of consecut ive 1s in t his array.
Input: [1,1,0,1,1,1]
Output: 3
Previous Next
Squares of a Sort ed Array Sliding Window
• Et c
You can t hink of it as anot her variat ion of t he t wo point er t echnique, where point ers are updat ed
separat ely based on a cert ain condit ion. Below is t he basic recipe for t his t ype of problems, in
pseudocode:
Previous Next
Max Consecut ive Ones Max Consecut ive Ones 3
Question Answer
Ret urn t he lengt h of t he longest (cont iguous) subarray t hat cont ains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Previous Next
Sliding Window St acks
Previous Next
Max Consecut ive Ones 3 Balanced Bracket s
Question Answer
Given a st ring s cont aining just t he charact ers '(' , ')' , '{' , '}' , '[' and ']' ,
det ermine if t he input st ring is valid.
Previous Next
St acks General St rings & Arrays
Previous Next
Balanced Bracket s Move Zeros
In-Place
Somet hing t o not e is t hat if we want t o reduce space complexit y, oft en we'll want t o perform our
algorit hm on t he input array inst ead of creat ing a new array. This is called in-place.
Answer Question
Given an array nums , writ e a funct ion t o move all 0 's t o t he end of it while maint aining t he
relat ive order of t he non-zero element s.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
Previous Next
General St rings & Arrays Unique Element s
BitMaps
Bit maps are arrays of specific sizes where every element is eit her True or False. They can be used for
many t hings but are an ext remely efficient met hod of st orage for cert ain algorit hms.
One example is t he act of whet her somet hing is open or closed, in or not in a set . Anyt hing t hat is
quant ifiable as a True / False operat ion.
Let 's say you port scan a websit e t o see what port s are open wit h Rust Scan. The posit ion in t he array
relat es t o t he port number. So we have port numbers 1 t hrough 5. We st art wit h all port s closed (False),
but our scanner report s t hat port 5 is open so we set it t o True.
We use t he size of t he array, t he indices, and True / False values t o map True / False values t o a
domain.
Question Answer
Implement an algorit hm t o det ermine if a st ring has all unique charact ers
Previous Next
Move Zeros Merge Sort ed Array
Question Answer
Given t wo sort ed int eger arrays nums1 and nums2, merge nums2 int o nums1 as one sort ed array.
Note:
• The number of element s init ialized in nums1 and nums2 are m and n respect ively.
• You may assume t hat nums1 has enough space (size t hat is equal t o m + n) t o hold addit ional
element s from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Previous Next
Unique Element s Mat rices
Previous Next
Merge Sort ed Array Valid Square
Question Answer
Given t he coordinat es of four point s in 2D space, ret urn whet her t he four point s could const ruct a
square.
The coordinat e (x,y) of a point is represent ed by an int eger array wit h t wo int egers.
Example:
Previous Next
Mat rices Mat rix Search Sequel
Question Answer
Writ e an efficient algorit hm t hat searches for a value in an m x n mat rix. This mat rix has t he
following propert ies:
• Int egers in each row are sort ed in ascending from left t o right .
• Int egers in each column are sort ed in ascending from t op t o bot t om.
Example:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Previous Next
Valid Square Unt it led
1. A simple base case (or cases) — a t erminat ing scenario t hat does not use recursion t o produce an
answer.
2. A set of rules, also known as recurrence relation t hat reduces all ot her cases t owards t he
base case.
Not e t hat t here could be mult iple places where t he funct ion may call it self.
When you hear a problem wit h t he following st at ement s, it 's oft en (t hough not always) a good
candidat e for recursion: "Design a problem t o comput e t he nt h....", "Writ e code t o list t he first n....",
"implement a met hod t o comput e all....", and so on.
People t ypically have about 50% accuracy in t heir "t his sounds like a recursive problem...." inst inct . Use
t hat inst inct , since t hat 50% is valuable. But don't be afraid t o look at t he problem in a different way,
even if you init ially t hought it seemed recursive. There's a 50% chance you are wrong
• Could t he problem be solved wit h an arbit rary number of nest ed for loops? For when you t hink
"t his problem would be easy if I can cont rol how many nest ed for loops are generat ed"
• Can you reframe t he problem as a search problem? If so, DFS can be used.
If we read t he code in order, we might t hink it 'll print 5, 4, 3, 2, 1 . But t his is wrong, t he recursive
call happens before we can cont inue t o t he end.
f(5)
f(4)
f(3)
f(2)
f(1)
f(0)
print(1)
print(2)
print(3)
print(4)
print(5)
The output is not always going to occur in the order it appears in our code
The most import ant t hing t o do is t o walk t hrough t he code exact ly as t he compiler would. As soon as
you st art assuming how t he code will behave and not reading t hrough it line-by-line, you’re screwed.
As funct ions get more complicat ed it becomes harder and harder t o act ually st ore everyt hing in your
head, especially since you have t o do your recursion out of order. The t ree will help you wit h t his.
Practice
I know t his may not sound like t he most fun t ask, but underst anding recursive code is crit ically
import ant . If you can underst and t he recursive code t hat ot her people writ e and why it works it will
make it exponent ially easier for you t o writ e your own recursive code.
Global Variable
The first opt ion (and t he only one here t hat I’d say you should probably never use) is t o st ore your
result int o a global variable. We all know t hat global variables aren’t a great solut ion when t here is
anot her opt ion, so t ry t o avoid t his if possible.
For demonst rat ion purposes, let ’s look at a funct ion t hat count s t he number of even values in an array.
Here’s how we could writ e t his code using a global variable:
int globalResult;
The key here is t hat we will simply creat e a global variable and updat e t he value as we recurse t hrough
our code. Whenever we find an even value in our array, we just increment t he global variable, similar t o
how we might solve t his problem it erat ively.
Passed Variable
We pass a variable t o our recursive funct ion t hat will updat e as it goes.
class ResultWrapper {
int result;
}
Not e in t his code, if we are using a language like Java, we have t o use some sort of Result Wrapper
class because we cannot direct ly pass a point er t o our funct ion and we will be updat ing t he value as we
go.
The advant age of t his approach is t hat it is generally t he easiest for most people t o underst and. It
also gives us t he opport unit y t o do t ail recursion, if t hat is somet hing t hat our language (and t he
problem) support s.
The reason t hat t his st rat egy is crit ical is t hat it will make it possible for us t o use t he FAST Met hod
t o solve dynamic programming problems. If we use one of t he previous t wo approaches, we are not
isolat ing our subproblems and so it becomes impossible for us t o act ually cache t he values t hat we
want .
Don’t bot her pract icing using global variables, since you really should never use t hat in your int erview.
However, I would recommend pract icing bot h of t he ot hers. Try doing a pract ice problem bot h ways.
See what t he similarit ies and differences are. The ext ra pract ice will do you good!
Backtracing
Backt racking is an essent ial st rat egy t hat we use in recursion. It essent ially allows us t o t ry different
possible result s wit hout act ually knowing ahead of t ime what t he right result is.
Consider t he Knight ’s Tour problem. In t his problem, we want t o find a pat h t hat a knight can follow on a
chessboard where it will visit each square exact ly once.
We don’t act ually know what t he right more is t o make ahead of t ime and a knight can make up t o 8
different moves from any one square, so we just have t o pick a move at random.
But obviously not all combinat ions of moves will t ake us t hrough a valid pat h. Some moves might t rap
us in a corner t hat we can’t get out of wit hout visit ing t he same square t wice.
The idea behind backt racking is simply t hat we ret race our st eps backwards and t hen t ry a different
pat h. This allows us t o t ry every different pat h unt il we ult imat ely find one t hat is valid.
Anot her example of t his t hat you’re likely already familiar wit h is dept h-first search in a t ree. When we
are looking for a node in a t ree, we consider t he left most branch first . Then what happens if we don’t
find t he node we’re looking for? We backt rack.
We go back up one level and t ry t he ot her child of t he parent node. If we st ill haven’t found what we
are looking for, we go back up t he t ree even furt her. This cont inues unt il we find what we are looking
for or have gone t hrough t he ent ire t ree.
• 0-1 Knapsack
• Sudoku Solving
• N Queens
Tail Recursion
Okay t his is t he most unnecessarily worried about concept in all of recursion. Tail recursion almost
never comes up in an int erview and isn’t even support ed by most major programming languages.
Tail recursion is an opt imizat ion t echnique t hat you can use t o improve t he space complexit y of a small
subset of recursive problems. To underst and how t his works, we do need t o t alk about space usage for
a second.
When you make recursive calls, t he comput er needs t o save t he st at e of t he current funct ion (all t he
variables, t he current posit ion t hat you’re execut ing at , et c) so t hat you can ret urn back aft er t he end
of t he recursive call.
Therefore, for every recursive call you make, you are using some space on t he call st ack. The more
recursive calls you make, t he more space you’re using.
Tail recursion allows us t o avoid having t o use ext ra space. Imagine t hat you writ e a funct ion where t he
very last line of t he funct ion is t he recursive call t hat immediat ely ret urns. Then do you really need t o
save t he previous funct ion st at e on t he call st ack?
No. You can just ret urn t he value from t he deepest level of your recursion direct ly t o t he t op.
That is what t ail recursion does for us. If we have a single recursive call t hat is t he very last t hing
before we ret urn, t hen we can opt imize out t he ext ra st ack space.
To look at our simple example from earlier, which of t hese is t ail recursive?
void f1(int n) {
if (n == 0) return;
f1(n-1);
print(n);
}
Or
void f2(int n) {
if (n == 0) return;
print(n);
f2(n-1);
}
Based on our definit ion, you can see t hat in f2(), t he very last t hing we do is our recursive call. f1() print s
aft er we make t he recursive call so we can’t opt imize it because we are going t o need t o ret urn back
t o t he previous funct ion so t hat we can call print (n).
So in limit ed circumst ances, t ail recursion can be useful. It is part icularly useful while doing funct ional
programming, since you are oft en doing basic t hings like it erat ion recursively t hat can be easily
opt imized.
However, most of t he t ime, t ail recursion won’t be helpful t o us. Chances are t he language t hat you’re
using won’t support it and on t op of t hat , many of t he examples t hat we will see in our int erviews will
require us t o make mult iple recursive calls wit hin our funct ion. If you have mult iple calls, t hey can’t bot h
be t he last t hing before we ret urn and so t ail recursion is out of t he quest ion.
Time Complexity
Remember when we represent ed our recursion as a t ree st ruct ure? Well t hat t ree st ruct ure can show
us very clearly t he number of recursive calls we’re making.
Wit h t his formula, we are now able t o simplify dramat ically int o t wo component s t hat we can more
easily calculat e.
How do we est imat e t he t ot al number of recursive calls wit hout drawing out t he whole t ree? Well if
we want ed t o comput e t he number of nodes in a t ree, we can look at t he height of t he t ree and t he
branching fact or.
The branching fact or is t he maximum number of child nodes any parent has in a t ree. If we have a binary
t ree, t he branching fact or will be 2.
To find t he branching fact or of our recursive t ree, we simply need t o look at t he maximum number of
recursive calls. In our Fibonacci funct ion, we call fibonacci(n-1) and fibonacci(n-2) every t ime, which
gives us a branching fact or of 2.
int f(n) {
if (n == 0) return 0;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += f(n-i);
}
return sum;
}
It seems hard as t he branching fact or depends on n . But remember, we only need t he worst case.
Now we have t he branching fact or and height of our recursive t ree, we can use t hese t o calculat e t he
t ime complexit y of our recursive funct ion using t his heurist ic:
$$number\_ of\_ nodes = O(branching\_ fact or^{dept h\_ of\_ recursion}*work\_ per\_ recursive\_ call)$$
Work per recursive call is simply t he amount of work t hat we’re doing in our funct ion ot her t han when
we call it recursively. If we have any sort of for loop, such as in t he example above, our work per
recursive call will be proport ional t o t hat loop, or O(n) in t his case.
Space Complexity
Recursive space complexit y is a bit easier for us t o comput e, but is also not exact ly t rivial.
The space does not depend on t he branching fact or, only on t he height and t hen amount of space used
per recursive call.
When we t hink about t his for a minut e, it makes sense. The branching fact or leads t o mult iple different
pat hs t hrough our recursive t ree. We have t o consider each of t hese separat ely for t he t ime complexit y
because t ime is addit ive. There is no way t o reuse t ime.
Space, however, can be reused. Each t ime we recurse down, we will be using more and more space.
However, once we ret urn from our recursive funct ion, we clear up space t hat can be reused for t he next
pat h.
It is, however, import ant t o remember t hat recursion does act ually use up space, since t hat is
somet hing t hat many people oft en t end t o forget .
How to Approach
Recursive solut ions, by definit ion, are built off of solut ions t o subproblems. Many t imes, t his will mean
simply t o comput e F(n) by adding somet hing, removing somet hing, or ot herwise changing t he solut ion
for F(n-1).
In ot her cases, you might solve t he problem for t he first half of t he dat a set , t hen t he second half, and
t hen merge t hose result s.
Bottom Up Approach
The bot t om-up approach is oft en t he must int uit ive. We st art wit h knowing how t o solve t he problem
for a simple case, like a list wit h only one element . Then we figure out how t o solve t he problem for
t wo element s, t hen for t hree element s and so on.
The key here is t o t hink about how you can build t he solut ion for one case off of t he previous case (or
mult iple previous cases).
Binary search works wit h a half and half approach. When we look for an element in an sort ed array, we
first figure out which half of t he array cont ains t he value. Then we recurse and search for it in t hat half.
Recursion Relation
There are t wo import ant t hings t hat one needs t o figure out before implement ing a recursive funct ion:
• recurrence relation : t he relat ionship bet ween t he result of a problem and t he result of it s
subproblems.
• base case : t he case where one can comput e t he answer direct ly wit hout any furt her recursion
calls. Somet imes, t he base cases are also called bottom cases, since t hey are oft en t he cases
where t he problem has been reduced t o t he minimal scale, t he bot t om, if we consider t hat dividing
t he problem int o subproblems is in a t op-down manner.
Once we figure out t he above t wo element s, t o implement a recursive funct ion we simply call t he
funct ion it self according t o t he recurrence relat ion unt il we reach t he base case.
To explain t he above point s, let 's look at a classic problem, Pascal's Triangle:
Pascal's t riangle are a series of numbers arranged in t he shape of t riangle. In Pascal's t riangle, t he
left most and t he right most numbers of each row are always 1. For t he rest , each number is t he sum of
t he t wo numbers direct ly above it in t he previous row.
Given t he above definit ion, one is asked t o generat e t he Pascal's Triangle up t o a cert ain number of
rows.
If you underst and each of t hese pat t erns and how t o code t hem, t hen you can apply t hese concept s t o
almost any recursive problems t hat might come up in your int erview. These 6 pat t erns are It erat ion,
Subproblems, Select ion, Ordering, Divide & Conquer, and Dept h First Search. For t he remainder of t his
sect ion, we will go int o each in more det ail.
Iteration
As you hopefully know, any problem t hat can be solved recursively can also be solved it erat ively and
vice versa. This is a fundament al concept behind funct ional languages, where you use recursion t o do
everyt hing; t here are no loops.
For example, consider t he problem of print ing a linked list in reverse order. There are plent y of
approaches we can t ake for t his problem, but recursion is uniquely concise:
void printReverse(Node n) {
if (n == null) return;
printReverse(n.next);
print(n.val);
}
For it erat ion, we simply make our recursive call on t he remainder of our input s, eit her by passing in t he
next node (as we did above) or by increment ing some index. While t his doesn’t come up t oo oft en, t his
is one of t he simplest applicat ions of recursion.
Subproblems
Wit h all t hat being said, t here are some problems t hat just lend t hemselves t o being broken down int o
subproblems.
One example of t his is t he Fibonacci problem t hat we’ve t alked about earlier in t his post . In t hat case,
even t he mat hemat ical definit ion of a Fibonacci sequence is recursive.
Anot her problem t hat frequent ly comes up is t he Towers of Hanoi problem. In t his case, we can simply
break down our problem by considering t he subproblem of moving t he t op n-1 disks. If we can move
t he t op n-1 disks, we just move all of t hem t o t he middle pin, move our bot t om disk t o t he dest inat ion
pin, and t hen move t he above disks again over t o t he dest inat ion pin. This works because all of t he
disks above our bot t om pin are not affect ed by any pins below t hem.
In problems like t his, you have t o look for t hose subproblems wit h which t o break up t he problem.
However, t here aren’t t oo many problems in t his cat egory, since most can be more explicit ly solved
wit h one of t he following pat t erns.
Selection
This is my favorit e pat t ern t o t est people on because it is one of t he most common pat t erns t o come
up in recursion (and dynamic programming). In t his pat t ern, we are simply finding all of t he combinat ions
of our input t hat mat ch a cert ain crit eria.
Consider for example t he 0-1 Knapsack Problem. In t his problem, we have a series of it ems t hat have
weight s and values. We want t o figure out what t he maximum value is t hat we can achieve while
remaining under some fixed weight .
Many people recognize t his as a dynamic programming problem, since it ’s a classic example, but let ’s
look at it from a recursive st andpoint .
What would be a brut e force solut ion t o t his problem? Well we can easily validat e for a given
combinat ion of it ems whet her it is under t he maximum weight , and we can also easily comput e t he
weight for any combinat ion. That means if we could just generat e all t he different combinat ions, we
could figure out t he opt imal answer.
Figuring out all t he combinat ions is t he core of a select ion problem. I like t he t erm “select ion” because
t he way our code works is t o simply include/exclude, or “select ”, each it em in our list .
The brut e force code t o generat e all combinat ions might look somet hing like t his (t his is simplified,
but you get t he idea):
List<List<Integer>> combinations(int[] n) {
List<List<Integer>> results = new LinkedList();
combinations(n, 0, results, new LinkedList<Integer>());
return results;
}
Once we underst and t his basic pat t ern, we can st art t o make opt imizat ions. In many cases, we may
act ually be able t o filt er out some combinat ions premat urely. For example, in t he Knapsack problem, we
can limit our recursion t o only consider combinat ions of it ems t hat st ay below t he prescribed weight .
If you spend t he majorit y of your t ime on any one pat t ern, it should be t his one. It comes up so
frequent ly in so many different forms. Some good problems t o get your st art ed are 0-1 Knapsack,
Word Break, and N Queens.
Ordering
This pat t ern is t he permut at ion t o Select ion’s combinat ion. Essent ially here we’re looking at any case in
which we want t o consider different orderings of our values. The most st raight forward problem here is
just t o figure out all of t he permut at ions of a given set of element s, alt hough just like wit h select ion,
we may add in addit ional rest rict ions.
Some examples of problems t hat fall under t his cat egory are Bogosort (sort ing a list of it ems by
generat ing all permut at ions and det ermining which is sort ed), finding all numbers t hat can be made
from a set of digit s t hat mat ch a cert ain propert y, det ermine all palindromic st rings t hat can be made
from a set of charact ers, and more.
In it s most simple form, t his is one way t hat we can brut e force generat e all permut at ions of a list . You
can also see an alt ernat ive approach here:
List<List<Integer>> permutations(Set<Integer> n) {
List<List<Integer>> results = new LinkedList();
permutations(n, results, new LinkedList<Integer>());
return results;
}
for (int i : n) {
// For now ignore concurrent modification issue
n.remove(i);
List<Integer> pathWithCurrent = new LinkedList(path);
pathWithCurrent.add(i);
permutations(n, results, pathWithCurrent);
n.add(i);
}
}
As you can hopefully see, t here is a lot of similarit y bet ween t his solut ion and t he combinat ions
solut ion above. By underst anding t hese t wo pat t erns and t heir variant s, you can cover a huge number of
t he different possible recursive problems you might be asked in your int erview.
Most frequent ly, t his pat t ern is used as part of common algorit hms t hat you should already know, such
as t he one I ment ioned above, but t here are a handful of problems for which t his can be valuable.
For example, consider t rying t o det ermine all of t he unique binary t rees t hat we can generat e from a
set of numbers. If you pick a root node, you simply need t o generat e all of t he possible variat ions of a
left and right subt ree.
Consider t rying t o find t he maximum and minimum value of a list using t he minimum number of
comparisons. One way t hat we can do t his is by split t ing t he list repeat edly, much t he same as how we
would do mergesort .
This t echnique generally applies t o t ree and sort ing/searching problems where we will be split t ing t he
problem space and t hen recombining t he result s.
There is also a slight ly different case in which D&C is very useful: Trying t o find all of t he ways t o group
a set . Imagine, for example, t hat you have a mat hemat ical funct ion. You want t o det ermine all of t he
different ways t hat you can group t he argument s. This can be done by recursively t rying split t ing your
formula at every different point . Here is an example of what t his code might look like. It uses a st ring,
but demonst rat es t he same concept :
List<String> parentheses(String s) {
if (s.length() == 1) {
List<String> result = new LinkedList<String>();
result.add(s);
return result;
}
return results;
}
In t his example, we t ake t he st ring and we t ry finding every different midpoint . For example “abcd”
becomes “(a)(bcd)”, “(ab)(cd)”, and “(abc)(d)”. Then we recursively apply t his t o each of t he halves of t he
st ring.
In t erms of t he det ails of t rees and graphs, I’m not going t o go in dept h here. There is way t oo much t o
cover so I’m going t o leave t hem t o t heir own st udy guides.
The main import ant t hing wit h DFS is t o underst and how not only t o search for a node in a t ree or graph
but also how t o act ually find t he pat h it self. If you can’t do t hat , you’re severely limit ing what you can
act ually do.
Here is what t he code might look like t o find t he pat h t o a specific node in a t ree:
List<Node> pathToNode(Node root, int val) {
if (root == null) return null;
if (root.value == val) {
List<Node> toReturn = new LinkedList<Node>();
toReturn.add(root);
return toReturn;
}
return null;
}
And t here’s not t hat much more t o it t han t hat . In most cases, you will use dept h first search as part of
a larger problem, rat her t han act ually having t o modify it in any significant way. Therefore t he most
import ant t hing is underst anding t he core of how DFS works.
Wit h t hese 6 recursive pat t erns, you will be able t o solve almost any recursive problem t hat you could
see in your int erview. The key is t o look for t hose pat t erns in t he problems t hat you are solving. If you
see t he pat t ern, use it . If not , t ry somet hing else. Different pat t erns will work bet t er for different
people, so do what feels right t o you.
Example
344. Reverse St ring
You can easily solve t his problem it erat ively, i.e. looping t hrough t he st ring st art ing from it s last
charact er. But how about solving it recursively?
Top Down
"Top-down" means t hat in each recursive call, we will visit t he node first t o come up wit h some values,
and pass t hese values t o it s children when calling t he funct ion recursively. So t he "t op-down" solut ion
can be considered as a kind of preorder t raversal. To be specific, t he recursive funct ion
top_down(root, params) works like t his:
For inst ance, consider t his problem: given a binary t ree, find it s maximum dept h.
We know t hat t he dept h of t he root node is 1 . For each node, if we know it s dept h, we will know t he
dept h of it s children. Therefore, if we pass t he dept h of t he node as a paramet er when calling t he
funct ion recursively, all t he nodes will know t heir dept h. And for leaf nodes, we can use t he dept h t o
updat e t he final answer. Here is t he pseudocode for t he recursive funct ion
maximum_depth(root, depth) :
1. return if root is null
2. if root is a leaf node:
3. answer = max(answer, depth) // update the answer if needed
4. maximum_depth(root.left, depth + 1) // call the function recursively for left
5. maximum_depth(root.right, depth + 1) // call the function recursively for righ
Bottom Up
"Bot t om-up" is anot her recursive solut ion. In each recursive call, we will first ly call t he funct ion
recursively for all t he children nodes and t hen come up wit h t he answer according t o t he ret urned
values and t he value of t he current node it self. This process can be regarded as a kind of postorder
t raversal. Typically, a "bot t om-up" recursive funct ion bottom_up(root) will be somet hing like t his:
Let 's go on discussing t he quest ion about maximum dept h but using a different way of t hinking: for a
single node of t he t ree, what will be t he maximum dept h x of t he subt ree root ed at it self?
If we know t he maximum dept h l of t he subt ree root ed at it s left child and t he maximum dept h r
of t he subt ree root ed at it s right child, can we answer t he previous quest ion? Of course yes, we can
choose t he maximum bet ween t hem and add 1 t o get t he maximum dept h of t he subt ree root ed at t he
current node. That is x = max(l, r) + 1 .
It means t hat for each node, we can get t he answer aft er solving t he problem for it s children.
Therefore, we can solve t his problem using a "bot t om-up" solut ion. Here is t he pseudocode for t he
recursive funct ion maximum_depth(root) :
Conclusion
Conclusion
It is not easy t o underst and recursion and find out a recursive solut ion for t he problem. It needs
pract ice.
When you meet a t ree problem, ask yourself t wo quest ions: Can you det ermine some paramet ers t o
help t he node know it s answer? Can you use t hese paramet ers and t he value of t he node it self t o
det ermine what should be t he paramet ers passed t o it s children? If t he answers are bot h yes, t ry t o
solve t his problem using a " top-down " recursive solut ion.
Or, you can t hink of t he problem in t his way: for a node in a t ree, if you know t he answer of it s children,
can you calculat e t he answer of t hat node? If t he answer is yes, solving t he problem recursively using a
bottom up approach might be a good idea.
In t he following sect ions, we provide several classic problems for you t o help you underst and t ree
st ruct ure and recursion bet t er.
Previous Next
Unt it led Backt racking
What is Backtracking?
Backt racking is where we increment ally build candidat es t o solut ions, and abandon candidat es
(backt rack) as soon we as det ermine t hat candidat e is not valid.
1. Make a change
2. Recurse
3. Undo t he change
Imagine recursive problems. Normally we can speed t hings up wit h dynamic programming, but
somet imes we don't even want t o consider a solut ion -- we just want t o t hrow it out .
1. Make a change
2. Recurse
3. Undo t he change
• For n queens: It erat e t hrough t he first row. If we can place a queen at a given column place it and
recurse for t he remaining rows. Then undo t he change by removing t he queen and moving t o t he
next column. Goal is when we have placed queen on nt h row
• Print all possible permut at ions: Init ialize an empt y St ring for result s. In t he input st ring it erat e
t hrough each charact er. For each charact er, remove it from input and add it t o result and recurse.
Then remove t he charact er from result and insert it back in same posit ion in input st ring. Goal is
when result size = n.
• Given n print all set s of valid parent heses t hat amount t o n: St art wit h blank input st ring and 2
numbers i, j init ialized t o n t hat denot e number of opening/closing parent heses remaining - you can
add opening parent heses t o t he st ring if i>0. You can add closing parent heses if j>i. If you can add
opening parent heses, add it t o st ringbuilder, recurse and t hen remove it from end of st ringbuilder. If
you can add closing parent heses add it t o st ringbuilder, recurse and t hen remove it from end of
st ringbuilder. Goal is when bot h i, j =0.
• Print all subset s of a set : For each charact er in set , remove it from input set add it t o result set
and if it has not been print ed already, print (goal is any set t hat has not been print ed already). Then
recurse for remaining element s. Then remove element from result set and add it back t o input set .
Pret t y much all t he backt racking problems I have done follows t his pat t ern.
Previous Next
Int roduct ion Permut at ions
Question Answer
Given a collect ion of distinct int egers, ret urn all possible permut at ions.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Previous Next
Backt racking Int roduct ion
This sect ion is based off of t he famous Leet code post , Dynamic Programming Pat t erns.
Loading...
LeetCode
• [LIST]
2. DP Pat t erns by @aat alyk
3. How t o solve DP - St ring? Templat e and 4 St eps t o be followed by @igooglet hings
4. Dynamic Programming Quest ions t hread by @karansingh1559
5. DP Classificat ion helpful not es by @adit yakrverma
6. How t o approach DP problems by @heroes3001
7. It erat ive DP for subset sum problems by @yuxiangmusic
8. DP problems summary (problem cat egorizat ion) by @richenyunqi
Next
Previous
Minimum (Maximum) Pat h t o Reach
Permut at ions
a Target
We can do t his by choosing t he minimum (maximum) pat h among all possible pat hs before t he current
st at e, and t hen add t he value for t he current st at e.
An example is:
Previous Next
Int roduct ion Min Cost Climbing St airs
Question Answer
Once you pay t he cost , you can eit her climb one or t wo st eps. You need t o find minimum cost t o
reach t he t op of t he floor, and you can eit her st art from t he st ep wit h index 0, or t he st ep wit h
index 1.
Previous
Next
Minimum (Maximum) Pat h t o Reach
Coin Change
a Target
Question Answer
You are given coins of different denominat ions and a t ot al amount of money amount . Writ e a
funct ion t o comput e t he fewest number of coins t hat you need t o make up t hat amount . If t hat
amount of money cannot be made up by any combinat ion of t he coins, ret urn -1 .
You may assume t hat you have an infinit e number of each kind of coin.
Previous Next
Min Cost Climbing St airs Minimum Pat h Sum
Given a m x n grid filled wit h non-negat ive numbers, find a pat h from t op left t o bot t om right which
minimizes t he sum of all numbers along it s pat h.
Note: You can only move eit her down or right at any point in t ime.
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Previous Next
Coin Change Triangle
We've seen dynamic programming by st art ing at t he t op of t he t ree and working down (t op-down
approach). What if we went from t he bot t om up (bot t om-up approach)?
Question Answer
Given a t riangle, find t he minimum pat h sum from t op t o bot t om. Each st ep you may move t o
adjacent numbers on t he row below.
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Next
Previous
Minimum Cost t o Move Chips t o The
Minimum Pat h Sum
Same Posit ion
Question Answer
We need t o move all t he chips t o the same position. In one st ep, we can change t he posit ion of
t he ith chip from position[i] t o:
Ret urn the minimum cost needed t o move all t he chips t o t he same posit ion.
Previous Next
Triangle Consecut ive Charact ers
Question Answer
Given a st ring s , t he power of t he st ring is t he maximum lengt h of a non-empt y subst ring t hat
cont ains only one unique charact er.
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Previous
Next
Minimum Cost t o Move Chips t o The
Perfect Squares
Same Posit ion
Given a posit ive int eger n, find t he least number of perfect square numbers (for example,
1, 4, 9, 16, ... ) which sum t o n.
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Previous Next
Consecut ive Charact ers Dist inct Ways
An example is:
Previous Next
Perfect Squares Climbing St airs
Question Answer
Each t ime you can eit her climb 1 or 2 st eps. In how many dist inct ways can you climb t o t he t op?
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Previous Next
Dist inct Ways Unique Pat hs
Question Answer
A robot is locat ed at t he t op-left corner of a m x n grid (marked 'St art ' in t he diagram below).
The robot can only move eit her down or right at any point in t ime. The robot is t rying t o reach t he
bot t om-right corner of t he grid (marked 'Finish' in t he diagram below).
Input: m = 3, n = 7
Output: 28
Example 2
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right c
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Previous Next
Climbing St airs Number of Dice Rolls wit h Target Sum
Last updat ed 4 years ago
Question Answer
You have d dice, and each die has f faces numbered 1, 2, ..., f .
Ret urn t he number of possible ways (out of fd t ot al ways) modulo 10^9 + 7 t o roll t he dice so
t he sum of t he face up numbers equals target .
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces. There is only one way to get a sum of 3.
Previous Next
Unique Pat hs Merging Int ervals
We can approach t his by finding all opt imal solut ions for every int erval and ret urn t he best possible
answer.
// from i to j
dp[i][j] = dp[i][k] + result[k] + dp[k+1][j]
Get t he best from t he left and right sides and add a solut ion for t he current posit ion.
return dp[0][n-1]
Previous Next
Number of Dice Rolls wit h Target Sum Minimum Cost Tree From Leaf Values
Question Answer
Given an array arr of posit ive int egers, consider all binary t rees such t hat :
• The values of arr correspond t o t he values of each leaf in an in-order t raversal of t he t ree.
(Recall that a node is a leaf if and only if it has 0 children.)
• The value of each non-leaf node is equal t o t he product of t he largest leaf value in it s left and
right subt ree respect ively.
Among all possible binary t rees considered, ret urn t he smallest possible sum of t he values of each
non-leaf node. It is guarant eed t his sum fit s int o a 32-bit int eger.
24 24
/ \ / \
12 4 6 8
/ \ / \
6 2 2 4
Previous Next
Merging Int ervals DP on St rings
Most of t he problems on t his pat t ern requires a solut ion t hat can be accept ed in O(n^2) complexit y.
// i - indexing string s1
// j - indexing string s2
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (s1[i-1] == s2[j-1]) {
dp[i][j] = /*code*/;
} else {
dp[i][j] = /*code*/;
}
}
}
Previous Next
Minimum Cost Tree From Leaf Values Levensht ein Dist ance
This quest ion is a leet code hard, but in my opinion it is easier t han t he next problem which is a
leet code medium.
Question Answer
Given t wo st rings word1 and word2 , ret urn the minimum number of operations required to
convert word1 to word2 .
• Insert a charact er
• Delet e a charact er
• Replace a charact er
Previous Next
DP on St rings Longest Common Subsequence
Question Answer
Given t wo st rings text1 and text2 , ret urn t he lengt h of t heir longest common subsequence.
A subsequence of a st ring is a new st ring generat ed from t he original st ring wit h some
charact ers(can be none) delet ed wit hout changing t he relat ive order of t he remaining charact ers.
(eg, "ace" is a subsequence of "abcde" while "aec" is not ). A common subsequence of t wo st rings is
a subsequence t hat is common t o bot h st rings.
Previous Next
Levensht ein Dist ance Int roduct ion
Loading...
LeetCode
We split t he search space int o t wo halves and only keep t he half t hat probably has t he search t arget
and t hrow away t he ot her half t hat cannot cont ain t he t arget .
In t his way, we reduce t he search sapce t o half at every st ep unt il we find t he t arget .
Binary search helps us reduce our O(n) linear search algorit hm int o O(log n).
We oft en want t o implement a slight ly modified binary search. Here are some t ypical problems we may
face:
• When do we exit t he loop? Should we use left < right or <= right ?
A rat her common misunderst anding of binary search is t hat people oft en t hink t his t echnique could only
be used in simple scenario like "Given a sort ed array, find a specific value in it ". As a mat t er of fact , it
can be applied t o much more complicat ed sit uat ions.
Aft er a lot of pract ice in Leet Code, I've made a powerful binary search t emplat e and solved many Hard
problems by just slight ly t wist ing t his t emplat e. I'll share t he t emplat e wit h you guys in t his post . I
don't want t o just show off t he code and leave. Most import ant ly, I want t o share t he logical t hinking:
how t o apply t his general t emplat e t o all sort s of problems. Hopefully, aft er reading t his post , people
wouldn't be pissed off any more when Leet Coding, "Holy sh*t ! This problem could be solved wit h binary
search! Why didn't I t hink of t hat before!"
What 's really nice of t his t emplat e is t hat , for most of t he binary search problems, we only need t o
modify t hree part s aft er copy-past ing t his t emplat e, and never need t o worry about corner cases and
bugs in code any more:
• Correct ly init ialize t he boundary variables left and right . Only one rule: set up t he boundary t o
include all possible elements;
• Decide ret urn value. Is it return left or return left - 1 ? Remember t his: after exiting the
while loop, left is the minimal ksatisfying the condition function;
• Design t he condition funct ion. This is t he most difficult and most beaut iful part . Needs lot s of
pract ice.
Below I'll show you guys how t o apply t his powerful t emplat e t o many Leet Code problems.
Previous Next
Longest Common Subsequence First Bad Version
Question Answer
You are a product manager and current ly leading a t eam t o develop a new product . Unfort unat ely,
t he lat est version of your product fails t he qualit y check. Since each version is developed based
on t he previous version, all t he versions aft er a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want t o find out t he first bad one, which
causes all t he following ones t o be bad.
You are given an API bool isBadVersion(version) which ret urns whet her version is bad.
Implement a funct ion t o find t he first bad version. You should minimize t he number of calls t o t he
API.
Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
Previous Next
Int roduct ion Sqrt (x)
Question Answer
Comput e and ret urn t he square root of x, where x is guarant eed t o be a non-negat ive int eger.
Since t he ret urn t ype is an int eger, t he decimal digit s are t runcat ed and only t he int eger part of
t he result is ret urned.
Input: 4
Output: 2
Previous Next
First Bad Version Search Insert Posit ion
Question Answer
Given a sort ed array of dist inct int egers and a t arget value, ret urn t he index if t he t arget is found.
If not , ret urn t he index where it would be if it were insert ed in order.
Previous Next
Sqrt (x) Advanced
As for t he quest ion "When can we use binary search?", my answer is t hat , If we can discover some
kind of monotonicity, for example, if condition(k) is True then condition(k + 1) is True ,
then we can consider binary search.
Previous Next
Search Insert Posit ion KoKo Eat ing Banana
Question Answer
Koko loves t o eat bananas. There are N piles of bananas, t he i -t h pile has piles[i]
bananas. The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eat ing speed of K . Each hour, she chooses some pile of
bananas, and eat s K bananas from t hat pile. If t he pile has less t han K bananas, she eat s all of
t hem inst ead, and won't eat any more bananas during t his hour.
Koko likes t o eat slowly, but st ill want s t o finish eat ing all t he bananas before t he guards come
back.
Ret urn t he minimum int eger K such t hat she can eat all t he bananas wit hin H hours.
Example 1:
Previous Next
Advanced Capacit y t o Ship Packages wit hin D Days
Question Answer
A conveyor belt has packages t hat must be shipped from one port t o anot her wit hin D days.
The i -t h package on t he conveyor belt has a weight of weights[i] . Each day, we load t he
ship wit h packages on t he conveyor belt (in t he order given by weights ). We may not load more
weight t han t he maximum weight capacit y of t he ship.
Ret urn t he least weight capacit y of t he ship t hat will result in all t he packages on t he conveyor
belt being shipped wit hin D days.
Note that the cargo must be shipped in the order given, so using a ship of capaci
Next
Previous
Minimum Number of Days t o Make
KoKo Eat ing Banana
m Bouquet s
Question Answer
Given an int eger array bloomDay , an int eger m and an int eger k .
We need t o make m bouquet s. To make a bouquet , you need t o use k adjacent flowers from
t he garden.
The garden consist s of n flowers, t he ith flower will bloom in t he bloomDay[i] and t hen can
be used in exactly one bouquet .
Ret urn the minimum number of days you need t o wait t o be able t o make m bouquet s from t he
garden. If it is impossible t o make m bouquet s ret urn -1.
Example 1:
Previous Next
Capacit y t o Ship Packages wit hin D Days Split array largest sum
Question Answer
Given an array nums which consist s of non-negat ive int egers and an int eger m , you can split t he
array int o m non-empt y cont inuous subarrays.
Previous Next
Minimum Number of Days t o Make Minimum Number of Days t o Make
m Bouquet s m Bouquet s
Question Answer
Given an int eger array bloomDay , an int eger m and an int eger k .
We need t o make m bouquet s. To make a bouquet , you need t o use k adjacent flowers from
t he garden.
The garden consist s of n flowers, t he ith flower will bloom in t he bloomDay[i] and t hen can
be used in exactly one bouquet .
Ret urn the minimum number of days you need t o wait t o be able t o make m bouquet s from t he
garden. If it is impossible t o make m bouquet s ret urn -1.
Example 1:
Previous Next
Split array largest sum Koko Eat ing Bananas
Question Answer
Koko loves t o eat bananas. There are N piles of bananas, t he i -t h pile has piles[i]
bananas. The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eat ing speed of K . Each hour, she chooses some pile of
bananas, and eat s K bananas from t hat pile. If t he pile has less t han K bananas, she eat s all of
t hem inst ead, and won't eat any more bananas during t his hour.
Koko likes t o eat slowly, but st ill want s t o finish eat ing all t he bananas before t he guards come
back.
Ret urn t he minimum int eger K such t hat she can eat all t he bananas wit hin H hours.
Example 1:
Previous
Next
Minimum Number of Days t o Make
Find K-t h Smallest Pair Dist ance
m Bouquet s
Question Answer
Given an int eger array, ret urn t he k-t h smallest distance among all t he pairs. The dist ance of a pair
(A, B) is defined as t he absolut e difference bet ween A and B.
Example 1:
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Previous Next
Koko Eat ing Bananas Ugly Number 3
Question Answer
Example 1:
Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
Next
Previous
Find t he Smallest Divisor Given
Find K-t h Smallest Pair Dist ance
a Threshold
Question Answer
Given an array of int egers nums and an int eger threshold , we will choose a posit ive int eger
divisor and divide all t he array by it and sum t he result of t he division. Find t he smallest divisor
such t hat t he result ment ioned above is less t han or equal t o threshold .
Each result of division is rounded t o t he nearest int eger great er t han or equal t o t hat element . (For
example: 7/3 = 3 and 10/2 = 5).
Example 1:
Next
Previous
Kt h smallest number in
Ugly Number 3
mult iplicat ion t able
Question Answer
Nearly every one have used t he Mult iplicat ion Table. But could you find out t he k-th smallest
number quickly from t he mult iplicat ion t able?
Given t he height m and t he lengt h n of a m * n Mult iplicat ion Table, and a posit ive int eger
k , you need t o ret urn t he k-th smallest number in t his t able.
Example 1:
Input: m = 3, n = 3, k = 5
Output:
Explanation:
The Multiplication Table:
1 2 3
2 4 6
3 6 9
Previous
Next
Find t he Smallest Divisor Given
Binary Trees
a Threshold
Preorder Traversal
Pre-order t raversal is t o visit t he root first . Then t raverse t he left subt ree. Finally, t raverse t he right
subt ree.
Queues
fn preOrderTrav(TreeNode Node){
if node != None:
visit(node);
preOrderTrav(node.left)
preOrderTrav(node.right)
}
In-order traversal
In-order t raversal is t o t raverse t he left subt ree first . Then visit t he root . Finally, t raverse t he right
subt ree.
When performed on a binary search t ree, it visits the nodes in ascending order (hence t he name in-
order)
St acks
fn inOrderTrav(TreeNode node){
if node != None:
inOrderTrav(node.left)
visit(node)
inOrderTrav(node.right)
}
Post Order
Visit s current node aft er it s child nodes (post -order, as it does it s node post )
fn postTrav(TreeNode node){
postTrav(node.left)
postTrav(node.right)
visit(node)
}
Previous
Next
Kt h smallest number in
Merging Binary Trees
mult iplicat ion t able
Question Answer
Given t wo binary t rees node0 and node1 , ret urn a merge of t he t wo t rees where each value is
equal t o t he sum of t he values of t he corresponding nodes of t he input t rees. If only one input
t ree has a node in a given posit ion, t he corresponding node in t he new t ree should mat ch t hat input
node.
0 7
/ \ / \
3 2 5 1
/
3
Ret urn
7
/ \
8 3
/
3
Constraints
Example 1
Input
Output
Question Answer
Given t he root of a binary t ree, ret urn the preorder traversal of its nodes' values.
Example 1:
Previous Next
Merging Binary Trees Binary Tree Post order Traversal
Question Answer
Given t he root of a binary t ree, ret urn the postorder traversal of its nodes' values.
Example 1:
Previous Next
Binary Tree Preorder Traversal Binary Tree Level Order Traversal
Question Answer
Given a binary t ree, ret urn t he level order t raversal of it s nodes' values. (ie, from left t o right , level
by level).
For example:
Given binary t ree [3,9,20,null,null,15,7] ,
3
/ \
9 20
/ \
15 7
[
[3],
[9,20],
[15,7]
]
Previous Next
Binary Tree Post order Traversal Binary Tree Inorder Traversal
Question Answer
Given t he root of a binary t ree, ret urn the inorder traversal of its nodes' values.
Example 1:
Previous Next
Binary Tree Level Order Traversal Symmet ric Tree
Question Answer
Given a binary t ree, check whet her it is a mirror of it self (ie, symmet ric around it s cent er).
1
/ \
2 2
/ \ / \
3 4 4 3
1
/ \
2 2
\ \
3 3
Next
Previous
Populat ing Next Right Point ers in
Binary Tree Inorder Traversal
Each Node
Question Answer
You are given a perfect binary tree where all leaves are on t he same level, and every parent has
t wo children. The binary t ree has t he following definit ion:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populat e each next point er t o point t o it s next right node. If t here is no next right node, t he next
point er should be set t o NULL .
Follow up:
• Recursive approach is fine, you may assume implicit st ack space does not count as ext ra space
for t his problem.
Example 1:
Question Answer
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populat e each next point er t o point t o it s next right node. If t here is no next right node, t he next
point er should be set t o NULL .
Follow up:
• Recursive approach is fine, you may assume implicit st ack space does not count as ext ra space
for t his problem.
Example 1:
Previous Next
Populat ing Next Right Point ers in 106. Const ruct Binary Tree from Inorder
Each Node and Post order Traversal
Last updat ed 4 years ago
Given inorder and post order t raversal of a t ree, const ruct t he binary t ree.
Note:
You may assume t hat duplicat es do not exist in t he t ree.
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
3
/ \
9 20
/ \
15 7
Previous
Next
Populat ing Next Right Point ers in Each
Serialise and Deserialise a Linked List
Node II
Question Answer
Serializat ion is convert ing a dat a st ruct ure or object int o a sequence of bit s so t hat it can be
st ored in a file or memory buffer, or t ransmit t ed across a net work connect ion link t o be
reconst ruct ed lat er in t he same or anot her comput er environment .
Design an algorit hm t o serialize and deserialize a binary search tree. There is no rest rict ion on
how your serializat ion/deserializat ion algorit hm should work. You need t o ensure t hat a binary
search t ree can be serialized t o a st ring, and t his st ring can be deserialized t o t he original t ree
st ruct ure.
Example 1:
Example 2:
Input: root = []
Output: []
Previous
Next
106. Const ruct Binary Tree from Inorder
Maximum Dept h of Binary Tree
and Post order Traversal
Question Answer
The maximum dept h is t he number of nodes along t he longest pat h from t he root node down t o
t he fart hest leaf node.
Example:
3
/ \
9 20
/ \
15 7
Next
Previous
Lowest Common Ancest or of a
Serialise and Deserialise a Linked List
Binary Tree
Question Answer
Given a binary t ree, find t he lowest common ancest or (LCA) of t wo given nodes in t he t ree.
According t o t he definit ion of LCA on Wikipedia: “The lowest common ancest or is defined bet ween
t wo nodes p and q as t he lowest node in T t hat has bot h p and q as descendant s (where we allow
a node to be a descendant of itself).”
Example 1:
Example 2:
Example 3:
Input: root = [1,2], p = 1, q = 2
Output: 1
Previous Next
Maximum Dept h of Binary Tree n-ary Trees
Tree Traversal
Previous
Next
Lowest Common Ancest or of a
Unt it led
Binary Tree
Problem Answer
A t ree is an undirect ed graph in which any t wo vert ices are connect ed by exact ly one pat h. In ot her
words, any connect ed graph wit hout simple cycles is a t ree.
Ret urn a list of all MHTs' root labels. You can ret urn t he answer in any order.
The height of a root ed t ree is t he number of edges on t he longest downward pat h bet ween t he
root and a leaf.
Previous Next
Unt it led Binary Search Trees
Basically, t he ent ire left side must always be smaller t han t he right on t he same level.
This definit ion can change slight ly. Under some condit ions, t he t ree cannot have duplicat e values. Or
t he duplicat e values will be on t he right side, or on t he left . All are valid, so check wit h your int erviewer.
When given a quest ion, many candidat es assume t he int erviewer means a binary search t ree.
Be sure t o ask!
A binary search tree implies that for each node, its left descendants are less than or equal to
the current node, which is less then the right descendants.
Balanced vs Unbalanced
Ask your int erviewer whet her t he t ree is balanced or unbalanced
Not e: balancing a t ree does not mean left and right subt rees are exact ly t he same size.
One way of t hinking about t his is t hat a balanced t ream means "not t erribly unbalanced". It 's balanced
enough t o ensure O(log n) insert and find, but it 's not necessarily as balanced as it could be.
Perfect t rees are rare in int erviews and in real life. Do not assume a binary t ree is perfect in an
int erview.
Next
Previous
Count ing Maximal Value Root s in
Minimum Height Trees
Binary Tree
Question Answer
Given a binary t ree root , count and ret urn t he number of nodes where it s value is great er t han or
equal t o t he values of all of it s descendant s.
6
/ \
3 2
/ \
6 4
Ret urn 4 since all nodes except for 2 meet t he crit eria.
Example 1
Input
root = [6, [3, null, null], [2, [6, null, null], [4, null, null]]]
Output
Previous Next
Binary Search Trees Count BST nodes in a range
Question Answer
Given a binary search t ree root , and int egers lo and hi , ret urn t he count of all nodes in root
whose values are bet ween lo and hi (inclusive).
For example, wit h t his t ree and lo = 5 and hi = 10 , ret urn 3 since only 7, 8, 9 are bet ween
[5, 10] .
3
/ \
2 9
/ \
7 12
/ \
4 8
Example 1
Input
Output
Previous
Next
Count ing Maximal Value Root s in
Invert a Binary Tree
Binary Tree
Question Answer
Given t he root of a binary t ree, find t he maximum value V for which t here exist different
nodes A and B where V = |A.val - B.val| and A is an ancest or of B .
Question Answer
Given t he root of a binary t ree, ret urn the sum of every tree node's tilt.
The tilt of a t ree node is t he absolute difference bet ween t he sum of all left subt ree node
values and all right subt ree node values. If a node does not have a left child, t hen t he sum of t he
left subt ree node values is t reat ed as 0 . The rule is similar if t here t he node does not have a
right child.
Previous
Next
Maximum Difference Bet ween Node
Pract ice
and Ancest or
Previous Next
Binary Tree Tilt What is a Linked List ?
You can also have doubly linked list s, which remembers it s previous node.
1. you need const ant -t ime insert ions/delet ions from t he list (such as in real-t ime comput ing where
t ime predict abilit y is absolut ely crit ical)
2. you don't know how many it ems will be in t he list . Wit h arrays, you may need t o re-declare and copy
memory if t he array grows t oo big
4. you want t o be able t o insert it ems in t he middle of t he list (such as a priorit y queue)
2. you know t he number of element s in t he array ahead of t ime so t hat you can allocat e t he correct
amount of memory for t he array
3. you need speed when it erat ing t hrough all t he element s in sequence. You can use point er mat h on
t he array t o access each element , whereas you need t o lookup t he node based on t he point er for
each element in linked list , which may result in page fault s which may result in performance hit s.
4. memory is a concern. Filled arrays t ake up less memory t han linked list s. Each element in t he array
is just t he dat a. Each linked list node requires t he dat a as well as one (or more) point ers t o t he
ot her element s in t he linked list .
Array List s (like t hose in .Net ) give you t he benefit s of arrays, but dynamically allocat e resources for
you so t hat you don't need t o worry t oo much about list size and you can delet e it ems at any index
wit hout any effort or re-shuffling element s around. Performance-wise, arraylist s are slower t han raw
arrays.
Previous Next
Pract ice Add Two Numbers
Question Answer
You are given t wo non-empty linked list s represent ing t wo non-negat ive int egers. The digit s are
st ored in reverse order, and each of t heir nodes cont ains a single digit . Add t he t wo numbers and
ret urn t he sum as a linked list .
You may assume t he t wo numbers do not cont ain any leading zero, except t he number 0 it self.
Previous Next
What is a Linked List ? Add Two Numbers 2
Question Answer
You are given t wo non-empty linked list s represent ing t wo non-negat ive int egers. The most
significant digit comes first and each of t heir nodes cont ain a single digit . Add t he t wo numbers
and ret urn it as a linked list .
You may assume t he t wo numbers do not cont ain any leading zero, except t he number 0 it self.
Follow up:
What if you cannot modify t he input list s? In ot her words, reversing t he list s is not allowed.
Example:
Previous Next
Add Two Numbers Reverse a Linked List
Question Answer
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Previous Next
Add Two Numbers 2 Tort oise & Hare Algorit hm
class Solution {
public:
ListNode* middleNode(ListNode* head) {
return slow;
}
};
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pointer1 = 1
pointer2 = 1
Alt hough t his doesn't hit all nodes in t he list , it can be useful t o have a point er t railing behind our hare
point er.
Previous Next
Reverse a Linked List Middle of t he Linked List
Last updat ed 4 years ago
Question Answer
Given a non-empt y, singly linked list wit h head node head , ret urn a middle node of linked list .
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NU
Previous Next
Tort oise & Hare Algorit hm Int roduct ion
First Method
Second Method
This is my personal favourit e met hod, but t o do t his you need t o know your powers of 2.
Powers of 2 are very import ant in comput er science. Binary is represent ed as 2 numbers, so if you have
3 circuit s t hen you will have 2³ numbers, 0 t hrough t o 7.
2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192.
And t o make an odd number, we add 1 t o t he list so t he list of numbers we need t o know becomes: 1, 2,
4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192.
Okay, say we want t o represent 15 as a binary number. First we need t o split up 15 so it can be made up
of powers of 2 + t he number 1. The nearest power of 2 t hat is less t han 15 is 8, so we’ll use t hat . 8 + 4
is 12. 8 + 4 + 2 is 14, so we’re very nearly t here! Now we just add a 1. 15 represent ed as powers of 2 is
8 + 4 + 2 + 1.
If t he number uses an 8, put a 1 in t he binary box under it t o represent t hat it uses an 8. I much prefer
t o use t his met hod t hough:
And t hen normally we would need t o reverse t he binary numbers, but in t his case because it ’s all just 1’s
we don’t need t o reverse. If we don’t reverse t hem, we get t he wrong binary number as binary is read
wit h t he highest order of magnit ude t o t he left , not t he lowest . Much like how in “10”, t he 1 is a whole
place higher t han t he 0; t he same applies for binary.
Binary Addition
Let ’s first review addit ion in decimal.
23 + 11
We first add 3 + 1, t hat equals 4. t hen we add 2 + 1, which is 3. So t he answer is 34. We add from t he
right t o t he left .
0 + 0 = 1
and
0 + 1 = 1
and
1 + 1 = 10
Try it yourself:
Also, pret t y much every operat or works in t he same way it does wit h binary as wit h decimal.
In Binary, numbers can be 4 bit , 8 bit , 16 bit , 32 bit and so on. If we have an 8 bit number, it ’ll be 8 digit s
long.
So let ’s say we have t he number 1 in 8-bit binary, t hat ’ll be represent ed as: 00000001 t o t urn t his
negat ive, we add a 1 t o t he front of it 10000001
Alt hough t his somet imes causes a problem. Given t he number 0 in 8-bit binary: 00000000 we can make
it negat ive by adding a 1 t o t he front of it . 10000000 But -0, what is t hat ? It ’s not hing. It ’s impossible.
And t hat ’s where t he problem comes from.
Two's Complement
We can make a binary number negat ive by applying two’s complement t o it wit hout t he need t o sign it .
• add a +1 t o t he number
So given t he number 15, which is 1111, in 8-bit binary it ’ll be: 00001111 So t o make t his negat ive we
invert all t he digit s: 11110000 t hen we add a 1 t o t he end 11110001 and now t his represent s -15! How
creat ive and cool!
But t his t ime we can ignore any carries t hat go off t he end.
So we use t he largest power of 2 t hat can fit bot h 5 and 3 int o it , which is 8. But t his t ime we make it
negat ive.
Now we simply add t hem. 1 + 1 is 0 carry 1, t he next line is 1 + 1 which is 0 so carry t hat , t he next line is
1 + 1 which is 0 so carry t hat , t he next line is 1 + 1 + 1 which is 1 carry 1, but t his t ime we can t hrow
away t he carry and we’re left wit h 1000 as an answer.
Many t hanks t o Jahan Ulhaque, Comput er Science St udent at Universit y of Liverpool for showing me
t his met hod.
Overflow
Overflow is when more bit s are st ored in t he binary value t han it could hold.
The correct result , 9, is t oo big t o fit int o 4 bit represent at ion, as t he 1 on t he front makes it negat ive
1.
If bot h input s t o an addit ion have t he same sign, and t he out put sign is different , overflow has
occurred.
Subtraction in Binary
Treat t his as addit ion but negat e t he second operand. So 4–3 is just 4 + (-3)
Which is just
Adding Numbers
Sum of t wo bit s can be obt ained by performing XOR (^) of t he t wo bit s. Carry bit can be obt ained by
performing AND (&) of t wo bit s.
Sum of 2 bits
0001
xor
0000
=
0001
0001
xor
0001
=
0000
1
and
1
=
1
We can t hen use left shift ing, which moves t he number 1 t o t he left .
Right Shifting
The arit hmet ic right shift essent ially divides by 2. The logical right shift would visually shift t he bit s.
In a logical right shift , we shift t he bit s and put a 0 in t he most significant bit . The It is indicat ed wit h a
>>> operat or.
On an 8-bit int eger (where t he sign bit is t he most significant bit ), t his would look like t he image below
(t hat I st ole out of cracking t he coding int erview):
Left Shifting
Does t he opposit e of right shift ing.
To mult iply a number, a binary shift moves all t he digit s in t he binary number along t o t he left and fills
t he gaps aft er t he shift wit h 0.
It also visually shift s t he bit s t o t he left .
00 << 1 = 100
return x
print(Add(15, 32))
Previous Next
Middle of t he Linked List Uncomplet ed
Previous Next
Int roduct ion Minimum Cost For Ticket s
Question Answer
In a count ry popular for t rain t ravel, you have planned some t rain t ravelling one year in advance.
The days of t he year t hat you will t ravel is given as an array days . Each day is an int eger from
1 t o 365 .
The passes allow t hat many days of consecut ive t ravel. For example, if we get a 7-day pass on
day 2, t hen we can t ravel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Ret urn t he minimum number of dollars you need t o t ravel every day in t he given list of days .
Previous Next
Uncomplet ed Minimum Falling Pat h Sum
Previous
Minimum Cost For Ticket s