Skip to content

Commit 3bb86fd

Browse files
committed
feat(book/exercises): interview q&a for linked lists and stacks
1 parent 06bd3f6 commit 3bb86fd

14 files changed

+658
-56
lines changed

book/D-interview-questions-solutions.asc

+203-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
<<<
12
[appendix]
23
[[d-interview-questions-solutions]]
34
== Interview Questions Solutions
@@ -29,7 +30,7 @@ include::interview-questions/max-subarray.js[tag=maxSubArrayBrute1]
2930

3031
This code is simple to understand; however, not very efficient. The runtime is `O(n^3)`.
3132

32-
If you noticed we adding up the numbers from `i` to `j` on each cycle. But, we can optimize this. We can keep a local variable and add the new number to it. That way, we don't have to revisit previous numbers.
33+
Notice we're adding up the numbers from `i` to `j` on each cycle. But, we can optimize this. We can keep a local variable and add the new number to it. That way, we don't have to revisit previous numbers.
3334

3435
[source, javascript]
3536
----
@@ -46,7 +47,7 @@ include::interview-questions/max-subarray.js[tag=description]
4647
include::interview-questions/max-subarray.js[tag=solution]
4748
----
4849

49-
The runtime is `O(n)` and a space complexity of `O(1)`.
50+
The runtime is `O(n)` and space complexity of `O(1)`.
5051

5152

5253

@@ -93,4 +94,203 @@ include::interview-questions/buy-sell-stock.js[tag=description]
9394
include::interview-questions/buy-sell-stock.js[tag=solution]
9495
----
9596

96-
The runtime is `O(n)` and a space complexity of `O(1)`.
97+
The runtime is `O(n)` and space complexity of `O(1)`.
98+
99+
100+
101+
:leveloffset: +1
102+
103+
=== Solutions for Linked List Questions
104+
(((Interview Questions Solutions, Linked Lists)))
105+
106+
:leveloffset: -1
107+
108+
109+
110+
111+
[#linkedlist-q-merge-lists]
112+
include::content/part02/linked-list.asc[tag=linkedlist-q-merge-lists]
113+
114+
We need to visit each node in both lists and merge them in ascending order. Note: We don't need to copy the values nor create new nodes.
115+
116+
Another case to take into consideration is that lists might have different lengths. So, if one list runs out, we have to keep taking elements from the remaining list.
117+
118+
*Algorithm*:
119+
120+
- Have a pointer for each list
121+
- While there's a pointer that is not null, visite them
122+
- Compare each list node's value and take the smaller one.
123+
- Advance the pointer of the taken node to the next one.
124+
125+
*Implementation*:
126+
127+
[source, javascript]
128+
----
129+
include::interview-questions/merge-lists.js[tag=description]
130+
include::interview-questions/merge-lists.js[tag=solution]
131+
----
132+
133+
Notice that we used a "dummy" node or "sentinel node" to have some starting point for the final list.
134+
135+
*Complexity Analysis*:
136+
137+
- Time: `O(m+n)`. Visiting each node from the list 1 and list 2 has a time complexity `O(m + n)`. `m` and `n` represent each list's length.
138+
- Space: `O(1)`. We reuse the same nodes and only change their `next` pointers. We only create one additional node, "the sentinel node."
139+
140+
141+
[#linkedlist-q-linkedlist-same-data]
142+
include::content/part02/linked-list.asc[tag=linkedlist-q-linkedlist-same-data]
143+
144+
We are given two linked lists that contain string data. We want to know if the concatenated strings from each list are the same.
145+
146+
The tricky part is that the same data can be distributed differently on the linked lists:
147+
148+
----
149+
L1: he -> ll -> o
150+
L2: h -> e -> llo
151+
----
152+
153+
One naive approach could be to go through each list's node and concatenate the strings. Then, we can check if they are equal.
154+
155+
[source, javascript]
156+
----
157+
include::interview-questions/linkedlist-same-data.js[tag=hasSameDataBrute1]
158+
----
159+
160+
Notice that the problem mentions that lists could be huge (millions of nodes). If the first character on each list is different, we are unnecessarily computing millions of nodes, when a straightforward check will do the job.
161+
162+
A better way to solve this problem is iterating over each character on both lists, and when we found mistmatch, we return `false` immediately. If they are the same, we still have to visit all of them.
163+
164+
*Algorithm*:
165+
166+
- Set a pointer to iterate over each node in the lists.
167+
- For each node, have an index (starting at zero) and compare if both lists have the same data.
168+
- When the index reaches the last character on the current node, we move to the next node.
169+
- If we found that a character from one list doesn't match the other, we return `false`.
170+
171+
*Implementation*:
172+
173+
[source, javascript]
174+
----
175+
include::interview-questions/linkedlist-same-data.js[tag=description]
176+
include::interview-questions/linkedlist-same-data.js[tag=solution]
177+
----
178+
179+
The function `findNextPointerIndex` is a helper to navigate each character on a linked list.
180+
Notice, that we increase the index (`i + 1`) on each iteration.
181+
If the index overflows, it moves to the next node and reset the index to zero.
182+
183+
184+
185+
*Complexity Analysis*:
186+
187+
- Time: `O(n)`. We go over all the characters on each list
188+
- Space: `O(1)`. Only using pointers and no auxiliary data structures.
189+
190+
191+
192+
:leveloffset: +1
193+
194+
=== Solutions for Stack Questions
195+
(((Interview Questions Solutions, Stack)))
196+
197+
:leveloffset: -1
198+
199+
[#stack-q-valid-parentheses]
200+
include::content/part02/stack.asc[tag=stack-q-valid-parentheses]
201+
202+
.We need to validate that brackets are properly opened and closed, following these rules:
203+
- An opened bracket must be close by the same type.
204+
- Open brackets mush be closed in the correct order.
205+
206+
This is a parsing problem, and usually, stacks are good candidates for them.
207+
208+
*Algorithm*:
209+
210+
- Create a mapping for each opening bracket, to its closing counterpart.
211+
- Iterate through the string
212+
- When we found an opening bracket, insert the corresponding closing bracket into the stack.
213+
- When we found a closing bracket, pop from the stack and make sure it corresponds to the current character.
214+
- Check the stack is empty. If there's a leftover, it means that something didn't close properly.
215+
216+
*Implementation*:
217+
218+
[source, javascript]
219+
----
220+
include::interview-questions/valid-parentheses.js[tag=description]
221+
include::interview-questions/valid-parentheses.js[tag=solution]
222+
----
223+
224+
*Complexity Analysis*:
225+
226+
- Time: `O(n)`. We iterate over each character of the string.
227+
- Space: `O(n)`. We use an auxiliary stack.
228+
229+
230+
231+
[#stack-q-daily-temperatures]
232+
include::content/part02/stack.asc[tag=stack-q-daily-temperatures]
233+
234+
The first solution that might come to mind it's using two for loops. For each element, we have visit each temperature ahead to find a bigger one.
235+
236+
[source, javascript]
237+
----
238+
include::interview-questions/daily-temperatures.js[tag=dailyTemperaturesBrute1]
239+
----
240+
241+
This solution is an `O(n^2)`. Can we do better? We can!
242+
243+
Here's an idea: start backward, so we know when there's a warmer temperature beforehand. The last element is always 0 (because there are no more temperatures ahead of it). We can place each element's index that we visit on a stack. If the current weather is bigger than the stack top, we remove it until a bigger one remains or the stack is empty. If the stack has a value, we calculate the number of days ahead. Otherwise, it is 0.
244+
245+
*Algorithm*:
246+
247+
- Traverse the daily temperatures backward
248+
- Push each temperature to a stack.
249+
- While the current temperature is larger than the one at the top of the stack, pop it.
250+
- If the stack is empty, then there's no warmer weather ahead, so it's 0.
251+
- If the stack has an element, calculate the index delta.
252+
253+
*Implementation*:
254+
255+
[source, javascript]
256+
----
257+
include::interview-questions/daily-temperatures.js[tag=description]
258+
include::interview-questions/daily-temperatures.js[tag=solution]
259+
----
260+
261+
The stack contains the indexes rather than the temperatures themselves.
262+
263+
*Complexity Analysis*:
264+
265+
- Time: `O(n)`. We visit each element on the array once.
266+
- Space: `O(1)`. The worst-case scenario is ascending order without duplicates. The stack will hold at most 70 items (100 - 30). If we didn't have the range restriction, then space complexity would be `O(n)`.
267+
268+
269+
270+
// [#linkedlist-q-FILENAME]
271+
// include::content/part02/linked-list.asc[tag=linkedlist-q-FILENAME]
272+
273+
// RESTATE REQUIREMENTS AND DESCRIPTIONS
274+
275+
// *Algorithm*:
276+
277+
// - STEP 1
278+
// - STEP 2
279+
// - STEP 2.1
280+
// - STEP 2.2
281+
282+
// *Implementation*:
283+
284+
// [source, javascript]
285+
// ----
286+
// include::interview-questions/FILENAME.js[tag=description]
287+
// include::interview-questions/FILENAME.js[tag=solution]
288+
// ----
289+
290+
// IMPLEMENTATION NOTES
291+
292+
// *Complexity Analysis*:
293+
294+
// - Time: `O(?)`. WHY?
295+
// - Space: `O(?)`. WHY?
296+

book/config

book/content/part02/array.asc

+17-17
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,30 @@ endif::[]
77
=== Array [[array-chap]]
88
(((Array)))
99
(((Data Structures, Linear, Array)))
10-
Arrays are one of the most used data structures. You probably have used it a lot but are you aware of the runtimes of `splice`, `shift`, `indexOf` and other operations? In this chapter, we are going deeper into the most common operations and their runtimes.
10+
Arrays are one of the most used data structures. You probably have used it a lot, but are you aware of the runtimes of `splice`, `shift`, `indexOf`, and other operations? In this chapter, we are going deeper into the most common operations and their runtimes.
1111

1212
==== Array Basics
1313

1414
An array is a collection of things (strings, characters, numbers, objects, etc.). They can be many or zero.
1515

16-
TIP: Strings are a collection of Unicode characters and most of the array concepts apply to them.
16+
TIP: Strings are a collection of Unicode characters, and most of the array concepts apply to them.
1717

1818
.Fixed vs. Dynamic Size Arrays
1919
****
20-
Some programming languages have fixedsize arrays like Java and {cpp}.
21-
Fixedsize arrays might be a hassle when your collection gets full, and you have to create a new one with a bigger size. For that, those programming languages also have built-in dynamic arrays: we have `vector` in {cpp} and `ArrayList` in Java. Dynamic programming languages like JavaScript, Ruby, and Python use dynamic arrays by default.
20+
Some programming languages have fixed-size arrays like Java and {cpp}.
21+
Fixed-size arrays might be a hassle when your collection gets full, and you have to create a new one with a bigger size. Those programming languages also have built-in dynamic arrays: we have `vector` in {cpp} and `ArrayList` in Java. Dynamic programming languages like JavaScript, Ruby, and Python use dynamic arrays by default.
2222
****
2323

2424
Arrays look like this:
2525

2626
.Array representation: each value is accessed through an index.
2727
image::image16.png[image,width=388,height=110]
2828

29-
Arrays are a sequential collection of elements that can be accessed randomly using an index. Let’s take a look into the different operations that we can do with arrays.
29+
Arrays are a sequential collection of elements that can be accessed randomly using an index. Let’s take a look at the different operations that we can do with arrays.
3030

3131
==== Insertion
3232

33-
Arrays are built-in into most languages. Inserting an element is simple; you can either add them at creation time or after initialization. Below you can find an example for both cases:
33+
Arrays are built-in in most languages. Inserting an element is simple; you can either add them at creation time or after initialization. Below you can find an example for both cases:
3434

3535
.Inserting elements into an array
3636
[source, javascript]
@@ -45,7 +45,7 @@ array2[100] = 2;
4545
array2 // [empty × 3, 1, empty × 96, 2]
4646
----
4747

48-
Using the index, you can replace whatever value you want. Also, you don't have to add items next to each other. The size of the array will dynamically expand to accommodate the data. You can reference values at whatever index you like: index 3 or even 100! In `array2`, we inserted 2 numbers but the length is 101 and there are 99 empty spaces.
48+
Using the index, you can replace whatever value you want. Also, you don't have to add items next to each other. The size of the array will dynamically expand to accommodate the data. You can reference values at whatever index you like: index 3 or even 100! In `array2`, we inserted 2 numbers, but the length is 101, and there are 99 empty spaces.
4949

5050
[source, javascript]
5151
----
@@ -54,7 +54,7 @@ console.log(array2); // [empty × 3, 1, empty × 96, 2]
5454
----
5555

5656

57-
The runtime for inserting elements using index is always is constant: _O(1)_.
57+
The runtime for inserting elements using an index is always is constant: _O(1)_.
5858

5959
===== Inserting at the beginning of the array
6060

@@ -72,7 +72,7 @@ As you can see, `2` was at index 0, now was pushed to index 1, and everything el
7272

7373
.JavaScript built-in `array.unshift`
7474
****
75-
The `unshift()` method adds one or more elements to the beginning of an array and returns the new length of the array.
75+
The `unshift()` method adds one or more elements to the beginning of an array and returns the array's new length.
7676
7777
Runtime: O(n).
7878
****
@@ -90,11 +90,11 @@ array.splice(1, 0, 111); // ↪️ [] <1>
9090
----
9191
<1> at position `1`, delete `0` elements and insert `111`.
9292

93-
The Big O for this operation would be *O(n)* since in worst case it would move most of the elements to the right.
93+
The Big O for this operation would be *O(n)* since, in the worst case, it would move most of the elements to the right.
9494

9595
.JavaScript built-in `array.splice`
9696
****
97-
The `splice()` method changes the contents of an arrayby removing existing elements or adding new elements. Splice returns an array containing the deleted elements.
97+
The `splice()` method changes an array's contents by removing existing elements or adding new elements. Splice returns an array containing the deleted items.
9898
9999
Runtime: O(n).
100100
****
@@ -116,15 +116,15 @@ Adding to the tail of the array doesn’t change other indexes. E.g., element 2
116116

117117
.JavaScript built-in `array.push`
118118
****
119-
The `push()` method adds one or more elements to the end of an array and returns the new length of the array.
119+
The `push()` method adds one or more elements to the end of an array and returns the array's new length.
120120
121121
Runtime: O(1).
122122
****
123123

124124
[[array-search-by-value]]
125125
==== Searching by value and index
126126

127-
Searching by index is very easy using the `[]` operator:
127+
Searching by the index is very easy using the `[]` operator:
128128

129129
.Search by index
130130
[source, javascript]
@@ -185,7 +185,7 @@ We would have to loop through the whole array (worst case) or until we find it:
185185

186186
==== Deletion
187187

188-
There are three possible scenarios for deletion (similar to insertion): removing at the beginning, middle or end.
188+
There are three possible deletion scenarios (similar to insertion): removing at the beginning, middle, or end.
189189

190190
===== Deleting element from the beginning
191191

@@ -224,7 +224,7 @@ array.splice(2, 1); // ↪️[2] <1>
224224
----
225225
<1> delete 1 element at position 2
226226

227-
Deleting from the middle might cause most of the elements of the array to move up one position to fill in for the eliminated item. Thus, runtime: O(n).
227+
Deleting from the middle might cause most of the array elements to move up one position to fill in for the eliminated item. Thus, runtime: O(n).
228228

229229
===== Deleting element from the end
230230

@@ -282,7 +282,7 @@ To sum up, the time complexity of an array is:
282282
// tag::array-q-max-subarray[]
283283
===== Max Subarray
284284

285-
Given an array of integers, find the maximum sum of consecutive elements (subarray).
285+
*AR-1*) _Given an array of integers, find the maximum sum of consecutive elements (subarray)._
286286
// end::array-q-max-subarray[]
287287

288288
[source, javascript]
@@ -297,7 +297,7 @@ _Solution: <<array-q-max-subarray>>_
297297
// tag::array-q-buy-sell-stock[]
298298
===== Best Time to Buy and Sell an Stock
299299

300-
You are given an array of integers. Each value represents the closing value of the stock on that day. You are only given one chance to buy and then sell. What's the maximun profit you can obtain? (Note: you have to buy first and then sell)
300+
*AR-2*) _You are given an array of integers. Each value represents the closing value of the stock on that day. You are only given one chance to buy and then sell. What's the maximum profit you can obtain? (Note: you have to buy first and then sell)_
301301
// end::array-q-buy-sell-stock[]
302302

303303
[source, javascript]

0 commit comments

Comments
 (0)
close