Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

big o sol #18

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions big_o_exercise/bigOExcercise.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Big O Notation Exercises

### Part 1

Simplify the following big O expressions as much as possible:

1. O(n + 10) > O(n)
2. O(100 * n) > O(n)
3. O(25) > O(1)
4. O(n^2 + n^3) > O(n^3)
5. O(n + n + n + n) > O(n)
6. O(1000 * log(n) + n) > O(n)
7. O(1000 * n * log(n) + n) > O(nlog(n))
8. O(2^n + n^2) > O(2^n)
9. O(5 + 3 + 1) > O(1)
10. O(n + n^(1/2) + n^2 + n * log(n)^10) > O^2)

### Part 2

Determine the time and space complexities for each of the following functions. If you're not sure what these functions do, copy and paste them into the console and experiment with different inputs!


// 1.

function logUpTo(n) {
for (var i = 1; i <= n; i++) {
console.log(i);
}
}

Time Complexity: O(n)
Space Complexity: O(1)

// 2.

function logAtMost10(n) {
for (var i = 1; i <= Math.min(n, 10); i++) {
console.log(i);
}
}

Time Complexity: O(1)
Space Complexity: O(1)

// 3.

function logAtLeast10(n) {
for (var i = 1; i <= Math.max(n, 10); i++) {
console.log(i);
}
}

Time Complexity: O(1) if n < 10. O(n) if n > 10
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you can just say it's O(n), since big O only cares about large values of n anyway. (no need to change your solution, just an FYI)

Space Complexity: O(1)

// 4.

function onlyElementsAtEvenIndex(array) {
var newArray = Array(Math.ceil(array.length / 2));
for (var i = 0; i < array.length; i++) {
if (i % 2 === 0) {
newArray[i / 2] = array[i];
}
}
return newArray;
}

Time Complexity: O(n)
Space Complexity: O(n)

// 5.

function subtotals(array) {
var subtotalArray = Array(array.length);
for (var i = 0; i < array.length; i++) {
var subtotal = 0;
for (var j = 0; j <= i; j++) {
subtotal += array[j];
}
subtotalArray[i] = subtotal;
}
return subtotalArray;
}

Time Complexity: O(n^2)
Space Complexity: O(n)