Computer Science Principles
Course Progress
0/0
Objectives in LxD
3.4 Strings
3.4 Strings
3.3 Mathematical Expressions
3.3 Math Expressions
3.2 Data Abstractions
3.2 Data Abstractions
3.1 Variables & Assignments
3.1 Variables and Assignments
3.1 Variables and Assignments (Sample)
Intro to Python
Intro to Javascript
Variables and HTML DOM (Sample)
3.5 Boolean Expressions (PY)
3.5 Boolean Expressions (JS)
3.8 Iterations
3.7 Nested Conditionals
3.6 Conditionals
3.8 Iterations
3.7 Nested Conditionals
3.6 Conditionals
3.13 Developing Procedures
3.12 Calling Procedures
3.10 Lists
3.13 Developing Procedures
3.10 Lists
3.9 Developing Algorithms
3.17 Algorithmic Efficiency
3.9 Algorithms
3.17 Algorithmic Efficiency
3.15 Random Numbers (pseudocode)
3.15 Random Numbers (js)
3.15 Random Numbers (py)
BI 3 Review
Sprint View
Week 7
3.17 Algorithmic Efficiency
3.17 Algorithmic Efficiency
1 min read
- Algorithmic Efficiency Hacks: Javascript
Algorithmic Efficiency Hacks: Javascript
Let’s test your knowledge on algorithmic efficiency!
Hack 1: How Much Time?
Objective: write the time complexity of the algorithm below using Big-O notation.
(don’t worry about special cases such as n = 1 or n = 0).
%%javascript
let n = 10; // change this value to test different outputs!
for (let i = 0; i < n * 2; i++) {
console.log(i);
}
//TODO: print the above algorithm's time complexity
//BE CAREFUL - This one might trick some people. Remember that Big-O notation shows how much an algorithm's time complexity GROWS, so coefficients don't matter...
<IPython.core.display.Javascript object>
Hack 2: Your Turn!
Objective: write an algorithm with O(n^2) time complexity.
%%javascript
const n = 10; // change this if you want.
//TODO: Write an algorithm with O(n^2) time complexity
//Hint: think about nested loops...
Hack 3: Gotta Go Fast!
Objective: Optimize this algorithm so that it has a lower time complexity without modifying the outer loop
%%javascript
const n = 10; // change this
let count = 0;
for(let i = 0; i < n; i++){ //Outer loop, DO NOT MODIFY
for(let j = 0; j < i; j++){
count ++;
}
}
console.log(count);
//TODO: Modify the algorithm so that it has a lower time complexity but same output, and keep the outer loop the same
//Hint: This algorithm has a time complexity of O(n^2).
<IPython.core.display.Javascript object>
Hack 4: Extra Challenge (you might also get extra credit for this one so u should do it)
Objective: Write an algorithm with a time complexity of O(n*log(n)).
n = int(input())
#TODO: Write an algorithm that has a more complicated time complexity than O(n^x).