You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This code is simple to understand; however, not very efficient. The runtime is `O(n^3)`.
31
32
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.
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.
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`.
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.
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)`.
Copy file name to clipboardExpand all lines: book/content/part02/array.asc
+17-17
Original file line number
Diff line number
Diff line change
@@ -7,30 +7,30 @@ endif::[]
7
7
=== Array [[array-chap]]
8
8
(((Array)))
9
9
(((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.
11
11
12
12
==== Array Basics
13
13
14
14
An array is a collection of things (strings, characters, numbers, objects, etc.). They can be many or zero.
15
15
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.
17
17
18
18
.Fixed vs. Dynamic Size Arrays
19
19
****
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.
22
22
****
23
23
24
24
Arrays look like this:
25
25
26
26
.Array representation: each value is accessed through an index.
27
27
image::image16.png[image,width=388,height=110]
28
28
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.
30
30
31
31
==== Insertion
32
32
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:
34
34
35
35
.Inserting elements into an array
36
36
[source, javascript]
@@ -45,7 +45,7 @@ array2[100] = 2;
45
45
array2 // [empty × 3, 1, empty × 96, 2]
46
46
----
47
47
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.
<1> at position `1`, delete `0` elements and insert `111`.
92
92
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.
94
94
95
95
.JavaScript built-in `array.splice`
96
96
****
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.
98
98
99
99
Runtime: O(n).
100
100
****
@@ -116,15 +116,15 @@ Adding to the tail of the array doesn’t change other indexes. E.g., element 2
116
116
117
117
.JavaScript built-in `array.push`
118
118
****
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.
120
120
121
121
Runtime: O(1).
122
122
****
123
123
124
124
[[array-search-by-value]]
125
125
==== Searching by value and index
126
126
127
-
Searching by index is very easy using the `[]` operator:
127
+
Searching by the index is very easy using the `[]` operator:
128
128
129
129
.Search by index
130
130
[source, javascript]
@@ -185,7 +185,7 @@ We would have to loop through the whole array (worst case) or until we find it:
185
185
186
186
==== Deletion
187
187
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.
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).
228
228
229
229
===== Deleting element from the end
230
230
@@ -282,7 +282,7 @@ To sum up, the time complexity of an array is:
282
282
// tag::array-q-max-subarray[]
283
283
===== Max Subarray
284
284
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)._
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)_
0 commit comments