package jan20;
public class InverseArray {
public static void main(String[] args) {
// Create and initialize the input array
// Time Complexity: O(1)
// Space Complexity: O(n) – storing input array of size n
int[] arr = new int[]{4, 0, 2, 3, 1};
// Create an output array to store the inverse
// Time Complexity: O(1)
// Space Complexity: O(n) – storing the result of inversion
int[] ans = new int[arr.length];
// Loop through the input array
// Time Complexity: O(n) – loop runs n times
// Space Complexity: O(1) – constant space used in loop
for (int i = 0; i < arr.length; i++) {
int index = arr[i]; // O(1)
ans[index] = i; // O(1)
}
// Print the inverse array
// Time Complexity: O(n) – printing all n elements
// Space Complexity: O(1)
for (int x : ans)
System.out.print(x + "\t");
}
}
| Case | Time Complexity | Explanation |
|---|
| Best Case | O(n) | Every element is processed once. |
| Average Case | O(n) | All elements are traversed and reassigned. |
| Worst Case | O(n) | Even if the array is in reverse or random order, all n elements are still processed once. |
No comments:
Post a Comment