In coding interviews and system design discussions, efficiency matters as much as correctness. Understanding time complexity and space complexity helps you build algorithms that scale to millions of users and terabytes of data. This guide explains complexities with Java examples, step-by-step analysis, and real-world applications.
In interviews, you are usually expected to give the Big-O (worst case) complexity.
int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}
⏱️ Time: O(n) → every element is checked.
💾 Space: O(1) → only one variable `max`.
void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
⏱️ Time: O(n²) → two nested loops.
💾 Space: O(1) → only a temporary variable.
void mergeSort(int[] arr, int l, int r) {
if (l < r) {
int mid = (l+r)/2;
mergeSort(arr, l, mid);
mergeSort(arr, mid+1, r);
merge(arr, l, mid, r);
}
}
⏱️ Time: O(n log n) → divide and merge steps.
💾 Space: O(n) → requires auxiliary arrays during merging.
int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
⏱️ Time: O(2^n) → exponential growth due to repeated calls.
💾 Space: O(n) → recursion stack depth.
Map map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
// Lookup
int age = map.get("Alice");
⏱️ Time: O(1) average, O(n) worst-case (hash collisions).
💾 Space: O(n) for storing all key-value pairs.
int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
⏱️ Time: O(log n) – halves the search space each step.
💾 Space: O(1).
Algorithm | Time Complexity | Space Complexity |
---|---|---|
Find Max | O(n) | O(1) |
Bubble Sort | O(n²) | O(1) |
Merge Sort | O(n log n) | O(n) |
Fibonacci (Recursive) | O(2^n) | O(n) |
HashMap Lookup | O(1) avg, O(n) worst | O(n) |
Binary Search | O(log n) | O(1) |
Mastering time and space complexity is a cornerstone for coding interviews and real-world system design. Always explain both when answering – it shows depth of understanding and readiness for scalable systems.
Read More: Explore more Java interview prep articles on LogicBrace.
0 Comments