Sunday, January 30, 2022

Inverse of an Array




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");
}
}


CaseTime ComplexityExplanation
Best CaseO(n)Every element is processed once.
Average CaseO(n)All elements are traversed and reassigned.
Worst CaseO(n)Even if the array is in reverse or random order, all n elements are still processed once.

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...