Skip to content

Commit 7b021d0

Browse files
committed
docs: add complexities
1 parent af6c80a commit 7b021d0

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

3sum/evan.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,14 @@ var threeSum = function (nums) {
4747

4848
return result;
4949
};
50+
51+
/**
52+
* Time Complexity: O(n^2)
53+
* The algorithm involves sorting the input array, which takes O(n log n) time.
54+
* The main part of the algorithm consists of a loop that runs O(n) times, and within that loop, there is a two-pointer technique that runs in O(n) time.
55+
* Thus, the overall time complexity is O(n log n) + O(n^2), which simplifies to O(n^2).
56+
*
57+
* Space Complexity: O(n)
58+
* The space complexity is O(n) due to the space needed for the sorted array and the result array.
59+
* Although the sorting algorithm may require additional space, typically O(log n) for the in-place sort in JavaScript, the dominant term is O(n) for the result storage.
60+
*/

top-k-frequent-elements/evan.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,16 @@ var topKFrequent = function (nums, k) {
2020

2121
return sorted.slice(0, k).map(([num]) => num);
2222
};
23+
24+
/**
25+
* Time Complexity: O(n log n)
26+
* - Counting the frequency of each element takes O(n) time.
27+
* - Sorting the entries by frequency takes O(n log n) time.
28+
* - Extracting the top k elements and mapping them takes O(k) time.
29+
* - Therefore, the overall time complexity is dominated by the sorting step, resulting in O(n log n).
30+
31+
* Space Complexity: O(n)
32+
* - The counter map requires O(n) space to store the frequency of each element.
33+
* - The sorted array also requires O(n) space.
34+
* - Therefore, the overall space complexity is O(n).
35+
*/

0 commit comments

Comments
 (0)