Time and Space Complexity Flashcards
1
Q
What is the time complexity of inserting into a balanced BST?
A
O(log n) for insertion, as the tree height is logarithmic in a balanced BST.
2
Q
What is the space complexity of a recursive algorithm?
A
O(h) where h is the recursion depth (stack frames).
Example: DFS on a tree has O(h) space, where h is tree height.
3
Q
When to use O(n) vs. O(log n) algorithms in C++?
A
Use O(log n) (e.g., binary search, balanced BST) for large datasets with sorted or structured data. Use O(n) (e.g., linear scan) for unsorted data or when simplicity is prioritized.