🔥 Java | Early Exit Optimization 🚀 | Beats 100% | Efficient HashMap Use | LeetCode #2661
IntuitionThe problem involves determining the earliest point at which either a row or column in a matrix mat is fully painted, given the sequence of numbers in
# Intuition
The problem involves determining the earliest point at which either a row or column in a matrix **mat** is fully painted, given the sequence of numbers in **arr**. Since both **arr** and **mat** contain all integers from 1 to (m×n), we can efficiently track the painting process by mapping each number to its index in **arr**.

# Approach
1. Mapping Elements:
- Create a **HashMap** to map each number from **arr** to its index for quick lookups.

2. Tracking Fully Painted Rows/Columns:
- Iterate through each row and column of the matrix.
- For each row/column, track the maximum index from **arr** of the elements in that row/column.
- Update the smallest index where a row or column is completely painted.

3. Early Exit:
- If the smallest index found reaches the minimum possible index for a fully painted row or column **(Math.min(n-1, m-1))**, return immediately to optimize performance.

# Complexity
- Time complexity:
O(n×m). We iterate over each cell in the matrix once, performing constant-time lookups in the **HashMap**.

- Space complexity:
O(n×m). The **HashMap** stores the mapping of each element in **arr** to its index, with a total of (n×m) elements.

# Code
```java []
class Solution {
    public int firstCompleteIndex(int[] arr, int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        Map<Integer, Integer> arrayMap = new HashMap<>();
        for(int i = 0; i < arr.length; i++){
            arrayMap.put(arr[i], i);
        }

        int smallestIndex = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++){
            int currSmallestIdx = -1;
            for(int j = 0; j < m; j++){
                int idx = arrayMap.get(mat[i][j]);
                currSmallestIdx = Math.max(currSmallestIdx, idx);
            }

            smallestIndex = Math.min(smallestIndex, currSmallestIdx);
            if(smallestIndex == Math.min(n-1,m-1)){
                return smallestIndex;
            }
        }

        for(int i = 0; i < m; i++){
            int currSmallestIdx = -1;
            for(int j = 0; j < n; j++){
                int idx = arrayMap.get(mat[j][i]);
                currSmallestIdx = Math.max(currSmallestIdx, idx);
            }
            
            smallestIndex = Math.min(smallestIndex, currSmallestIdx);
            if(smallestIndex == Math.min(n-1,m-1)){
                return smallestIndex;
            }
        }

        return smallestIndex;
    }
}
```
['Java']