Skip to content

Commit

Permalink
add: time complexity examples in js
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Feb 19, 2025
1 parent 288b82e commit 570353f
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions data_structures/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ This section contains Data Structure and Algorithms in Java, Typescript and Fron
- [Prefix](./src/KeyPatterns/Prefix/README.md)
- [NeetCode 150](./neetcode_150/)
- [Javascript Questions](./js_questions)
- [Time and Space Complexity](./time_space_complexity/README.md)

## Docs

Expand Down
9 changes: 9 additions & 0 deletions data_structures/time_space_complexity/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Time and Space Complexity

## Time Complexity

- Measures how the execution time of an algorithm increases with input size (n)

## Space Complexity

- Measures how much memory an algorithm needs as input size (n) increases.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Constant Time - 0(1)
* @description
* - Time doesn't depend on input size
* @param {number[]} arr
*/
function getFirstElement(arr) {
return arr[0];
}
console.log(getFirstElement([1, 2, 3]));
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Linear Time - O(n)
* @description
* - Time grows proportionally with input size
* @param {number[]} arr
*/
function printAll(arr) {
for (let i = 0; i < arr.length; i++) {
console.log('arr --> ', arr[i]);
}
}
printAll([1, 2, 3]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Logarithmic Time - O(log n)
* @param {number[]} arr
* @param {number} target
* @returns {number}
*/
function binarySearch(arr, target) {
let left = 0,
right = arr.length - 1;

while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
arr[mid] < target ? (left = mid + 1) : (right = mid - 1);
}
return -1;
}

const result = binarySearch([1, 3, 5, 7, 9], 5);
console.log('result', result);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Quadratic Time - O(n²)
* @description
* - Nested Loops cause exponential growth.
* @param {number[]} arr
*/
function printPair(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
console.log(arr[i], arr[j]);
}
}
}
printPair([1, 2, 3, 4, 5, 6]);

0 comments on commit 570353f

Please sign in to comment.