question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
find-products-of-elements-of-big-array | Detailed Explanation | Beats 82.71% of Users | 😺✨ | detailed-explanation-beats-8271-of-users-wi7q | Intuition:\n\nThe problem seems to involve determining the products of elements within specific ranges of numbers, under certain modular arithmetic constraints. | Sci-fi-vy | NORMAL | 2024-07-05T07:14:56.919438+00:00 | 2024-07-05T07:14:56.919467+00:00 | 18 | false | # Intuition:\n\nThe problem seems to involve determining the products of elements within specific ranges of numbers, under certain modular arithmetic constraints. My initial thought is to decompose the problem into smaller parts: counting occurrences of specific bits and then using those counts to compute the results for each query efficiently.\n\n# Approach:\n\n1. **Helper Functions**:\n - `cnt1(num)`: This function calculates the cumulative count of `1` bits up to a given number `num`.\n - `acc0(num)`: This function calculates the cumulative count of `0` bits, weighted by their position, up to a given number `num`.\n\n2. **Main Counting Function**:\n - `count(bound)`: This function determines the effective count of bits up to a boundary `bound`. It does this by:\n - Finding the target number where the boundary is located.\n - Calculating the cumulative count of bits up to that target.\n - Adjusting the count based on the remaining bits within the boundary.\n\n3. **Processing Queries**:\n - For each query, which consists of a range (`low`, `high`) and a modulus (`mod`), we:\n - Use the `count` function to find the effective counts of bits within the range.\n - Compute the product of `2` raised to the power of the difference in bit counts, modulo `mod`.\n\n4. **Return the Results**:\n - Collect results for all queries in a list and return.\n\n# Complexity\n- **Time complexity**:\n - The `cnt1` and `acc0` functions run in $$O(log n)$$ time since they iterate through the bit lengths of the numbers.\n - The `count` function involves a binary search and bit-level operations, leading to a complexity of $$O(log^2 n)$$.\n - Each query is processed in $$O(log^2 n)$$ time, making the overall complexity for `q` queries $$O(q log^2 n)$$.\n\n- **Space complexity**:\n - The space complexity is $$O(1)$$ since we only use a constant amount of additional space for the computations.\n\n# Don\'t Forget to Upvote!!\uD83D\uDE3A\n\n# Python Code:\n\n```python\nclass Solution:\n def findProductsOfElements(self, queries: List[List[int]]) -> List[int]:\n \n # Helper function to count the cumulative number of \'1\' bits up to num\n def cnt1(num: int) -> int:\n res = 0\n for i in range(num.bit_length()):\n cur = num % (1 << (i + 1))\n res += (num - cur) // 2 \n if cur >= 1 << i:\n res += cur + 1 - (1 << i)\n return res\n \n # Helper function to count the cumulative weighted number of \'0\' bits up to num\n def acc0(num: int) -> int:\n res = 0\n for i in range(num.bit_length()):\n cur = num % (1 << (i + 1))\n res += (num - cur) // 2 * i\n if cur >= 1 << i:\n res += (cur + 1 - (1 << i)) * i\n return res\n \n # Function to calculate the bit count for a given boundary\n def count(bound: int) -> int:\n # Find the target number where bound is located\n target = bisect_left(range(bound), bound, key=cnt1)\n rest = bound - cnt1(target - 1)\n cnt = acc0(target - 1)\n \n # Adjust the count based on remaining bits\n for i in range(target.bit_length()):\n if target & (1 << i):\n cnt += i\n rest -= 1\n if not rest:\n break\n return cnt\n \n # Process each query and compute the product of elements in the given range\n return [pow(2, count(high + 1) - count(low), mod) for low, high, mod in queries]\n```\n | 0 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
find-products-of-elements-of-big-array | Python | Counting | python-counting-by-aryonbe-c8yp | Code\n\n#based on https://leetcode.com/problems/find-products-of-elements-of-big-array/solutions/5145201/c-bit-count-and-binary-search-clean-code-with-a-lot-exp | aryonbe | NORMAL | 2024-06-19T07:18:05.062075+00:00 | 2024-06-19T07:18:05.062103+00:00 | 12 | false | # Code\n```\n#based on https://leetcode.com/problems/find-products-of-elements-of-big-array/solutions/5145201/c-bit-count-and-binary-search-clean-code-with-a-lot-explanitions/\nclass Solution:\n def findProductsOfElements(self, queries: List[List[int]]) -> List[int]:\n def sumAndCountBitsUpToVal(val):\n bitSum = 0\n bitCnt = 0\n bit = 0\n j = 1\n while j <= val:\n cur = (val >> (bit+1)) << bit\n cur += ((val%j)+1)*((val%(j<<1)) >= j)\n bitCnt += cur\n bitSum += bit*cur\n j <<= 1\n bit += 1\n return bitSum, bitCnt\n def getValueFromIndex(idx):\n low, high = 1, 1<<50\n while low < high:\n mid = (low + high)//2\n if sumAndCountBitsUpToVal(mid)[1] < idx:\n low = mid + 1\n else:\n high = mid\n return low\n def prefixSumUpToIndex(idx):\n val = getValueFromIndex(idx)\n bitSum, bitCnt = sumAndCountBitsUpToVal(val)\n while bitCnt > idx:\n i = val.bit_length()\n bitSum -= i-1\n bitCnt -= 1\n val -= (1<<(i-1))\n return bitSum\n return [pow(2, prefixSumUpToIndex(j+1)-prefixSumUpToIndex(i), mod) for i,j,mod in queries]\n \n \n``` | 0 | 0 | ['Python3'] | 0 |
find-products-of-elements-of-big-array | Binary Search + concept of set bits | binary-search-concept-of-set-bits-by-nit-uhav | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | NitishSinghIITKGP | NORMAL | 2024-06-14T15:11:13.257781+00:00 | 2024-06-14T15:11:13.257806+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long int\nll setBits(ll n,ll x){\n return (n/(1LL<<(x+1)))*(1LL<<x)+max(0LL,(n%(1LL<<(x+1)))-(1LL<<x)+1);\n}\nll setBits(ll n){\n ll ans=0;\n for(ll i=0;i<60;i++) ans+=setBits(n,i);\n return ans;\n}\n\nclass Solution {\n ll mod;\n ll poww(ll a,ll b){\n if(a==1 or a==0 or b==1) return a%mod;\n if(b==0) return 1;\n ll ans=poww(a,b/2);\n ans=(ans%mod*ans%mod)%mod;\n if(b%2) ans=(ans%mod*a%mod)%mod;\n return ans;\n }\n\n ll find_ele(ll v){\n ll low=1,high=1e15;\n ll ans;\n while(low<=high){\n ll mid=(low+high)/2;\n if(setBits(mid)>=v) ans=mid,high=mid-1;\n else low=mid+1;\n }\n return ans;\n }\n ll solve(ll a,ll b){\n ll f=find_ele(a),s=find_ele(b); \n if(f==s){\n ll st=a-setBits(f-1); \n ll e=b-setBits(s-1); \n vector<ll>sb; \n for(ll i=0;i<60;i++){\n if(f & (1LL<<i)) sb.push_back(i);\n }\n ll ans=1;\n for(ll i=st-1;i<e;i++) ans*=(1LL<<sb[i]);\n return ans%mod;\n }\n vector<ll>temp(60,0);\n for(ll i=0;i<60;i++){\n if(s-1>f) temp[i]=setBits(s-1,i)-setBits(f,i);\n } \n ll st=a-setBits(f-1); \n vector<ll>sb; \n for(ll i=0;i<60;i++){\n if(f & (1LL<<i)) sb.push_back(i);\n }\n for(ll i=st-1;i<sb.size();i++) temp[sb[i]]++;\n sb.clear(); \n ll e=b-setBits(s-1); \n for(ll i=0;i<60;i++){\n if(s & (1LL<<i)) sb.push_back(i);\n }\n for(int i=0;i<e;i++) temp[sb[i]]++; \n ll ans=1; \n for(ll i=0;i<60;i++){\n if(temp[i]){\n ans=(ans * poww(1LL<<i,temp[i]))%mod;\n }\n }\n return ans%mod;\n }\npublic:\n vector<int> findProductsOfElements(vector<vector<long long>>& queries) {\n vector<int>ans;\n for(auto q:queries){\n mod=q[2];\n ans.push_back(solve(q[0]+1,q[1]+1));\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-products-of-elements-of-big-array | Bit Manipulation + Binary Search + Cyclic Property Of Bits | 65 ms | bit-manipulation-binary-search-cyclic-pr-m2v9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rohitsadhu | NORMAL | 2024-06-11T19:16:29.401149+00:00 | 2024-06-11T19:16:29.401172+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(q * log(1e15))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(q)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long bin_exp(long long a, long long b, long long mod){\n long long res = 1;\n while(b){\n if(b & 1){\n res = (res * a) % mod;\n }\n a = (a * a) % mod;\n b >>= 1;\n }\n return res;\n }\n unsigned long long f(long long num, int i){\n // returns the count of i-th bit set in range [0...num]\n // based on the cyclic property of bits\n unsigned long long a = (num + 1) / (1LL << (i+1));\n a = a * (1LL << i);\n long long excess = ((num + 1) % (1LL << (i+1))) - (1LL << i);\n return a + max(excess, 0LL);\n }\n unsigned long long g(long long num){\n unsigned long long sum = 0;\n for(int i=0; i<63; i++){\n unsigned long long t = f(num, i);\n sum += t;\n }\n return sum;\n }\n unsigned long long g_bit(long long num){\n unsigned long long sum = 0;\n for(int i=0; i<63; i++){\n unsigned long long t = f(num, i);\n sum += t * i;\n }\n return sum;\n }\n long long binary_search(long long k){\n long long low = 1, high = 1e15;\n while(low <= high){\n long long mid = low + ((high - low) >> 1);\n unsigned long long set_bits = g(mid);\n if(set_bits >= k){\n high = mid - 1;\n }else{\n low = mid + 1;\n }\n }\n return low;\n }\n vector<int> findProductsOfElements(vector<vector<long long>>& queries) {\n int q = queries.size();\n vector<int> v;\n for(auto& query: queries){\n long long lb = query[0]+1, ub = query[1]+1, mod = query[2];\n long long lb_num = binary_search(lb), ub_num = binary_search(ub);\n\n unsigned long long diff1 = lb - g(lb_num-1);\n unsigned long long diff2 = ub - g(ub_num-1);\n\n if(lb_num == ub_num){\n long long c = 0;\n unsigned long long ans = 1;\n for(int i=0; i<63; i++){\n if(lb_num & (1LL << i)){\n c++;\n if(c>=diff1 && c<=diff2){\n ans = ans * (1LL << i);\n ans %= mod;\n }\n }\n }\n v.push_back(ans);\n continue;\n }\n\n unsigned long long mid_part_sum = max(0ULL, g_bit(ub_num-1) - g_bit(lb_num));\n\n unsigned long long mid_part = bin_exp(2, mid_part_sum, mod);\n\n unsigned long long excess = 1;\n // for left part which is uneven\n int a = 0;\n for(int i=0; i<63; i++){\n if(lb_num & (1LL << i)){\n a++;\n if(a >= diff1){\n excess = excess * (1LL << i);\n excess %= mod;\n }\n }\n }\n // for right part which is uneven\n int b = 0;\n for(int i=0; i<63; i++){\n if(ub_num & (1LL << i)){\n b++;\n if(b <= diff2){\n excess = excess * (1LL << i);\n excess %= mod;\n }\n }\n }\n unsigned long long ans = (mid_part * excess) % mod;\n v.push_back(ans);\n }\n return v;\n }\n};\n``` | 0 | 0 | ['Binary Search', 'Bit Manipulation', 'C++'] | 0 |
find-products-of-elements-of-big-array | Beats 99.58% | beats-9958-by-lostsyntax-alv5 | Approach\n#### Powerful Array Generation:\n- Start by generating powerful arrays for each integer.\n- A powerful array for an integer x is the shortest sorted a | LostSyntax | NORMAL | 2024-05-23T22:15:54.948515+00:00 | 2024-07-17T03:22:34.071714+00:00 | 27 | false | # Approach\n#### **Powerful Array Generation:**\n- Start by generating powerful arrays for each integer.\n- A powerful array for an integer x is the shortest sorted array of powers of two that sum up to x. For example, the powerful array for 11 is [1, 2, 8].\n#### **Building big_nums Array:**\n- Concatenate the powerful arrays for every positive integer i in ascending order to form the big_nums array.\n- For example, big_nums starts as [1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...].\n#### **Precomputation:**\n- Precompute values to optimize subsequent queries.\n- Precompute prefix products modulo a large modulus for efficient computation of products of subsequences of big_nums.\n#### **Handling Queries:**\n- For each query [fromi,toi,modi]:\n - Calculate the sum of powers for the range [fromi,toi] using precomputed values.\n - Calculate the difference in sum of powers between toi and fromi.\n - Use modular exponentiation to compute the product modulo modi, efficiently.\n - Store the result in the answer vector.\n#### **Return Results:**\n- Return the answer vector containing the results of each query.\n\n# Complexity\n- Time complexity:\n**O(N\u2217Log(M))** where Q is the number of queries, and x represents the maximum values in the queries.\n- Space complexity:\n**O(Log(M))** where Q is the number of queries, and x represents the maximum values in the queries.\n\n# Code\n```\n#include <vector>\n#include <algorithm>\n\nclass Solution {\npublic:\n std::vector<int> findProductsOfElements(std::vector<std::vector<long long>>& queries) {\n std::vector<int> ans;\n\n for (const auto& query : queries) {\n long long from = query[0];\n long long to = query[1];\n int mod = query[2];\n\n if (mod == 1) {\n ans.push_back(0);\n continue;\n }\n\n long long sumPowersFrom = sumPowersFirstKBigNums(from);\n long long sumPowersTo = sumPowersFirstKBigNums(to + 1);\n long long diffSumPowers = sumPowersTo - sumPowersFrom;\n int product = modPow(2, diffSumPowers, mod);\n ans.push_back(product);\n }\n\n return ans;\n }\n\nprivate:\n long long sumPowersFirstKBigNums(long long k) {\n if (k == 0) return 0;\n\n long long num = firstNumberHavingSumBitsTillGreaterThan(k);\n long long sumPowers = sumPowersTill(num - 1);\n long long remainingCount = k - sumBitsTill(num - 1);\n\n for (int power = 0; remainingCount > 0; ++power) {\n if (num & (1LL << power)) {\n sumPowers += power;\n --remainingCount;\n }\n }\n\n return sumPowers;\n }\n\n long long firstNumberHavingSumBitsTillGreaterThan(long long k) {\n long long l = 1, r = k;\n while (l < r) {\n long long m = l + (r - l) / 2;\n if (sumBitsTill(m) < k)\n l = m + 1;\n else\n r = m;\n }\n return l;\n }\n\n long long sumBitsTill(long long x) {\n long long sumBits = 0;\n for (long long powerOfTwo = 1; powerOfTwo <= x; powerOfTwo <<= 1) {\n sumBits += (x / (2LL * powerOfTwo)) * powerOfTwo;\n sumBits += std::max(0LL, x % (2LL * powerOfTwo) + 1 - powerOfTwo);\n }\n return sumBits;\n }\n\n long long sumPowersTill(long long x) {\n long long sumPowers = 0;\n for (long long powerOfTwo = 1, power = 0; powerOfTwo <= x; powerOfTwo <<= 1, ++power) {\n sumPowers += (x / (2LL * powerOfTwo)) * powerOfTwo * power;\n sumPowers += std::max(0LL, x % (2LL * powerOfTwo) + 1 - powerOfTwo) * power;\n }\n return sumPowers;\n }\n\n int modPow(long long x, long long n, int mod) {\n int result = 1;\n x %= mod;\n while (n > 0) {\n if (n % 2 == 1)\n result = static_cast<int>((result * x) % mod);\n x = (x * x) % mod;\n n >>= 1;\n }\n return result;\n }\n};\n``` | 0 | 0 | ['Binary Search', 'Dynamic Programming', 'Bit Manipulation', 'C++'] | 0 |
find-products-of-elements-of-big-array | Optimal Approach in Swift 🚦 Find Products of elements of Big Array | optimal-approach-in-swift-find-products-8xs1a | \n## Intuition\nThe problem involves calculating the product of numbers within a given range where the numbers are represented by their binary powers of 2. Each | lebon | NORMAL | 2024-05-18T00:18:08.414781+00:00 | 2024-05-18T00:32:08.541884+00:00 | 7 | false | \n## Intuition\nThe problem involves calculating the product of numbers within a given range where the numbers are represented by their binary powers of 2. Each power of 2 follows a specific pattern. To solve the problem efficiently, we can utilize these patterns to determine the counts of each power of 2 in the given range and then calculate the resulting product modulo a given value.\n\n## Approach\n1. **Process Each Query:**\n - For each query, get the start (`s`) and end (`t`) indices and the modulo value (`mod`).\n - Adjust the end index by adding 1 because the range is inclusive.\n\n2. **Binary Search for Upper Bound:**\n - Use binary search to find the highest number `n1` where the sum of the count of powers of 2 in integers from 0 to `n1-1` is less than or equal to `s`.\n - Repeat the process for `t` to find `n2`.\n\n3. **Get Counts of Powers of 2:**\n - Calculate the counts of each power of 2 for numbers up to `n1` and `n2`.\n - Adjust these counts to match exactly `s` and `t` by incrementing the counts until they sum up to the desired target.\n\n4. **Compute Range Counts:**\n - Subtract the counts obtained for `s` from the counts obtained for `t` to get the counts for the range `[s, t)`.\n\n5. **Calculate Product:**\n - Use these counts to calculate the product of powers of 2 modulo `mod`.\n - For each power of 2, compute its contribution and handle the rollovers to the next higher power.\n\n6. **Final Adjustment for Highest Power:**\n - For the highest power of 2, continue reducing the count by doubling the base and updating the product.\n\n## Complexity\n- **Time complexity:** \n - Binary search in the given range [1, 100000000000000] will take $$O(\\log(\\text{MAX}))$$ iterations.\n - Calculating the sum of frequencies for each power of 2 will take $$O(\\log(\\text{MAX}))$$ time.\n - Adjusting the counts and calculating the product will take $$O(\\log(\\text{MAX})$$ time.\n - For $$Q$$ queries, the total time complexity is $$O(Q \\cdot \\log^2(\\text{MAX}))$$.\n\n- **Space complexity:**\n - The space used for storing counts of powers of 2 is $$O(\\log(\\text{MAX}))$$.\n - The space complexity is $$O(\\log(\\text{MAX}))$$.\n\n\n\n\n```swift []\nclass Solution {\n // Function to find products of elements for each query\n func findProductsOfElements(_ queries: [[Int]]) -> [Int] {\n var response = [Int](repeating: 0, count: queries.count)\n \n // Process each query individually\n for (i, query) in queries.enumerated() {\n let s = Int64(query[0]) // Start index\n let t = Int64(query[1]) + 1 // End index\n let mod = Int64(query[2]) // Modulo value\n response[i] = solve(s, t, mod) // Solve for the current query\n }\n \n return response\n }\n \n // Function to solve a single query\n private func solve(_ s: Int64, _ t: Int64, _ mod: Int64) -> Int {\n // Get the highest number x such that the sum of count of \n // powers of 2 in integers in the range [0, x-1] is <= s\n let n1: Int64 = s > 0 ? getNextHigher(1, 100000_00000_00000, s) : 0\n var c1: [Int64] = s > 0 ? getLowerCounts(n1) : Array(repeating: 0, count: 51)\n adjust(&c1, n1, s) // Adjust counts for s\n \n // Get the highest number x such that the sum of count of \n // powers of 2 in integers in the range [0, x-1] is <= t\n let n2: Int64 = getNextHigher(1, 100000_00000_00000, t)\n var c2: [Int64] = getLowerCounts(n2)\n adjust(&c2, n2, t) // Adjust counts for t\n \n // Calculate counts of each power of 2 in the desired range [s, t)\n for i in 0..<50 {\n c2[i] -= c1[i]\n }\n \n // Calculate powers of 2 modulo mod\n var pow = [Int64](repeating: 1, count: 50)\n for i in 1..<50 {\n pow[i] = (pow[i - 1] << 1) % mod\n }\n \n // Calculate the product of powers of 2\n var product: Int64 = 1\n var next: Int64 = 2\n c2[50] = 0\n \n // Iterate through each power of 2\n for i in 1..<50 {\n // Calculate remainder and division\n let remainder = Int((c2[i] * Int64(i)) % (Int64(i) + 1))\n let division = (c2[i] * Int64(i)) / (Int64(i) + 1)\n // Update product\n product = (product * pow[remainder]) % mod\n \n // Roll over the division to the next higher power of 2\n c2[i + 1] += division\n next <<= 1\n }\n \n // Calculate product for the highest power of 2\n var base = next % mod\n while c2[50] > 0 {\n if c2[50] % 2 == 1 {\n product = (product * base) % mod\n }\n base = (base * base) % mod\n c2[50] >>= 1\n }\n \n return Int(product % mod)\n }\n \n // Function to adjust counts\n private func adjust(_ counts: inout [Int64], _ x: Int64, _ target: Int64) {\n var index = 0\n var x = x\n // Increment counts until it matches target\n while counts[50] != target {\n if x == 0 {\n print("Error")\n break\n }\n if x % 2 != 0 {\n counts[index] += 1\n counts[50] += 1\n }\n x >>= 1\n index += 1\n }\n }\n \n // Function to get the next higher number for which the sum of count of \n // powers of 2 is <= target\n private func getNextHigher(_ from: Int64, _ to: Int64, _ target: Int64) -> Int64 {\n if from == to {\n return from\n }\n let mid = from + (to + 1 - from) / 2\n let counts = getLowerCounts(mid)\n if counts[50] > target {\n return getNextHigher(from, mid - 1, target)\n } else {\n return getNextHigher(mid, to, target)\n }\n }\n \n // Function to get counts of each power of 2 less than x\n private func getLowerCounts(_ x: Int64) -> [Int64] {\n var counts = [Int64](repeating: 0, count: 51)\n var total: Int64 = 0\n var i = 0\n var next: Int64 = 1\n // Calculate counts for each power of 2\n while next < x {\n counts[i] = (x / (2 * next)) * next + max((x % (2 * next)) - next, 0)\n total += counts[i]\n i += 1\n next <<= 1\n }\n // Store total count at the end of the array\n counts[50] = total\n return counts\n }\n}\n``` | 0 | 0 | ['Array', 'Binary Search', 'Swift'] | 0 |
find-products-of-elements-of-big-array | 2 Solutions | Simulation, Bit Mask + Binary Search | 2-solutions-simulation-bit-mask-binary-s-0awh | Solution-1: Simualtion (TLE -- Passes 98.41% TCs)\n1. STEP-1: Identify max number from queries -- O(500)\n2. STEP-2: generate bigNums array for intergers 1 to m | shahsb | NORMAL | 2024-05-17T14:44:22.331191+00:00 | 2024-05-17T14:46:07.917560+00:00 | 23 | false | # Solution-1: Simualtion (TLE -- Passes 98.41% TCs)\n1. **STEP-1:** Identify max number from queries -- O(500)\n2. **STEP-2:** generate bigNums array for intergers 1 to maxNo. -- O(N) \n3. **STEP-3:** Iterate over each quey and generate result -- O(q * N)\n4. **STAT:** TLE -- 746 / 758 test cases passed -- 98.41%\n# Solution-2: Binary Search + Bit Mask\n\n# Code (Solution-1):\n```\n#define ll long long\n#define ull unsigned long long\nclass Solution {\npublic:\n // SOL-1: SIMULATION -- TC: O(Q*N), SC: O(N) -- TLE -- 746 / 758 test cases passed -- 98.41%\n vector<int> findProductsOfElements(vector<vector<long long>>& queries) \n {\n // STEP-1) Identify max number from queries -- O(500)\n ll maxNo = getMaxFromQueries(queries);\n \n // STEP-2) generate bigNums array for intergers 1 to maxNo. -- O(N) \n vector<ll> bigNums = generateBigNums(maxNo);\n\n // STEP-3) Iterate over each quey and generate result -- O(q * N)\n vector<int> ans;\n for ( auto query : queries )\n {\n ll start = query[0], end = query[1], mod = query[2];\n ull prod = 1;\n for ( ll i=start; i<=end; i++) {\n prod *= bigNums[i];\n }\n ans.push_back(prod%mod);\n }\n return ans;\n }\n \n ll getMaxFromQueries(vector<vector<ll>>& queries)\n {\n ll ans = 0;\n for ( auto query : queries ) {\n ans = max(ans, query[1]);\n }\n return ans;\n }\n \n vector<ll> generateBigNums(ll maxNo)\n {\n vector<ll> bigNums;\n for ( ll i=1; i<=maxNo+1; i++ )\n {\n bitset<25> a(i);\n string s = a.to_string();\n //cout << s << " ";\n reverse(s.begin(), s.end());\n for ( int i=0; i<s.size(); i++ )\n {\n if ( s[i] == \'1\' )\n bigNums.push_back(pow(2,i));\n }\n }\n return bigNums;\n }\n};\n```\n# Code (Solution-2):\n```\nusing LL = long long;\n\nclass Solution {\npublic:\n vector<int> findProductsOfElements(vector<vector<LL>>& queries) {\n vector<int> result;\n result.reserve(queries.size());\n for (const auto& query : queries) {\n LL prefix_sum_1 = prefixSumTillIndex(query[0]);\n LL prefix_sum_2 = prefixSumTillIndex(query[1] + 1);\n\n result.push_back(pow(2, prefix_sum_2 - prefix_sum_1, query[2]));\n }\n\n return result;\n }\n\nprivate:\n // Count the bits for all numbers from 1 to `value - 1`.\n // Return the bit value sum and total count.\n pair<LL, LL> sumAndCountBitsBeforeValue(LL value) {\n LL bit_sum = 0;\n LL bit_count = 0;\n for (LL bit = 0, power = 1; power < value; bit++, power <<= 1) {\n LL cur = (value >> (bit + 1)) << bit;\n cur += max(0LL, (value % (power << 1)) - power);\n bit_count += cur;\n bit_sum += bit * cur;\n }\n return {bit_sum, bit_count};\n }\n\n LL getValueFromIndex(LL index) {\n index++;\n LL low = 1, high = 1LL << 50;\n\n while (low < high) {\n LL mid = low + (high - low) / 2;\n if (sumAndCountBitsBeforeValue(mid + 1).second < index) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n }\n\n LL prefixSumTillIndex(LL index) {\n LL value = getValueFromIndex(index);\n auto [bit_sum, bit_count] = sumAndCountBitsBeforeValue(value);\n // Also include the last value\'s partial bits.\n if (bit_count < index) {\n for (int bit = 0; bit_count < index; bit++, value >>= 1) {\n bit_sum += bit * (value % 2);\n bit_count += value % 2;\n }\n }\n return bit_sum;\n }\n\n // Calculate `(x ^ y) % mod` by converting the y into binary bits.\n int pow(LL x, LL y, int mod) {\n if (y <= 0) {\n return 1 % mod;\n }\n x %= mod;\n LL result = 1;\n while (y) {\n if (y & 1) {\n result = multiply(result, x, mod);\n }\n x = multiply(x, x, mod);\n y >>= 1;\n }\n return result;\n }\n\n int multiply(LL x, LL y, int mod) {\n return ((x % mod) * (y % mod)) % mod;\n }\n};\n``` | 0 | 0 | ['C', 'Simulation', 'Binary Tree', 'Bitmask'] | 0 |
find-products-of-elements-of-big-array | Just a runnable solution | just-a-runnable-solution-by-ssrlive-i6l6 | \n\nimpl Solution {\n pub fn find_products_of_elements(queries: Vec<Vec<i64>>) -> Vec<i32> {\n let mx = 1_000_000_000_000_006;\n let lim = 60;\ | ssrlive | NORMAL | 2024-05-13T06:06:15.566715+00:00 | 2024-05-13T06:06:15.566736+00:00 | 23 | false | \n```\nimpl Solution {\n pub fn find_products_of_elements(queries: Vec<Vec<i64>>) -> Vec<i32> {\n let mx = 1_000_000_000_000_006;\n let lim = 60;\n let mut ret = vec![];\n\n let mul = |x: i64, y: i64, m: i64| -> i64 {\n let x = x % m;\n let y = y % m;\n let res = x * y;\n if res >= m {\n res % m\n } else {\n res\n }\n };\n\n let mod_pow = |x: i64, y: i64, m: i64| -> i64 {\n if y <= 0 {\n return 1;\n }\n let mut ans = 1;\n let mut x = x % m;\n let mut y = y;\n while y != 0 {\n if y & 1 == 1 {\n ans = mul(ans, x, m);\n }\n x = mul(x, x, m);\n y >>= 1;\n }\n ans\n };\n\n let calc = |n: i64| -> i64 {\n if n <= 0 {\n return n;\n }\n let mut lo = 1;\n let mut hi = mx;\n while lo <= hi {\n let mid = (lo + hi) / 2;\n let mut sum = 0;\n for i in 0..lim {\n let p = 1_i64 << (i + 1);\n let mut cur = ((mid + 1) / p) * (1_i64 << i);\n cur += 0_i64.max((mid + 1) % p - (1_i64 << i));\n sum += cur;\n }\n if sum >= n {\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n hi + 1\n };\n\n let calc2 = |n: i64, tot: i64| -> Vec<i64> {\n let mut cnt = vec![0; lim];\n if n <= 0 {\n return cnt;\n }\n let mut sum = 0;\n for (i, cnt_i) in cnt.iter_mut().enumerate().take(lim) {\n let p = 1_i64 << (i + 1);\n let mut cur = (n / p) * (1_i64 << i);\n cur += 0_i64.max(n % p - (1_i64 << i));\n sum += cur;\n *cnt_i = cur;\n }\n if sum < tot {\n for (i, cnt_i) in cnt.iter_mut().enumerate().take(lim) {\n if sum >= tot {\n break;\n }\n if (n >> i) & 1 == 1 {\n *cnt_i += 1;\n sum += 1;\n }\n }\n }\n cnt\n };\n\n for q in queries {\n let v1 = calc2(calc(q[1] + 1), q[1] + 1);\n let v2 = calc2(calc(q[0]), q[0]);\n\n let mut val = 1;\n for i in 0..lim {\n let p = 1_i64 << i;\n let temp = mod_pow(p, v1[i] - v2[i], q[2]);\n val = (val * temp) % q[2];\n }\n ret.push(val as i32);\n }\n ret\n }\n}\n\n``` | 0 | 0 | ['Rust'] | 0 |
find-products-of-elements-of-big-array | scala | scala-by-len_master-4cj9 | scala\nobject Solution {\n def findProductsOfElements(queries: Array[Array[Long]]): Array[Int] = {\n def calc(p: Int, lim: Long): Long = {\n val len = | len_master | NORMAL | 2024-05-13T03:23:02.986330+00:00 | 2024-05-13T03:23:02.986362+00:00 | 3 | false | ```scala\nobject Solution {\n def findProductsOfElements(queries: Array[Array[Long]]): Array[Int] = {\n def calc(p: Int, lim: Long): Long = {\n val len = 1L << p\n val len2 = len * 2\n val ret = lim / len2 * len + (if (lim % len2 >= len) lim % len2 - len + 1 else 0)\n ret\n }\n\n def countOne(x: Long): Long = {\n def g(x: Long, p: Int): Long =\n if ((1L << p) > x) 0L\n else calc(p, x) + g(x, p + 1)\n\n g(x, 0)\n }\n\n def findPos(x: Long): (Long, Int) = {\n @scala.annotation.tailrec\n def binarySearch(head: Long, tail: Long): (Long, Int) =\n if (head >= tail) (head, (x - countOne(head - 1)).toInt)\n else {\n val mid = (head + tail) >> 1\n if (countOne(mid) >= x) binarySearch(head, mid)\n else binarySearch(mid + 1, tail)\n }\n\n binarySearch(1L, x)\n }\n\n def gao1(x: Long, L: Int, R: Int, M: Int): Long = {\n var ret = 1L\n var p = 0\n var i = 0\n while ((1L << p) <= x) {\n if ((x >> p & 1) == 1) {\n i += 1\n if (L <= i && i <= R) ret = (1L << p) % M * ret % M\n }\n p += 1\n }\n ret\n }\n\n def power(a: Long, b: Long, M: Int): Long = {\n @scala.annotation.tailrec\n def g(aa: Long, bb: Long, y: Long): Long =\n if (bb == 0) y\n else {\n val new_y = if ((bb & 1) == 1) y * aa % M else y\n val new_aa = aa * aa % M\n val new_bb = bb >> 1\n g(new_aa, new_bb, new_y)\n }\n\n g(a, b, 1L)\n }\n\n\n def gao2(L: Long, R: Long, M: Int): Long = {\n @scala.annotation.tailrec\n def g(p: Int, ret: Long): Long =\n if ((1L << p) > R) ret\n else {\n val cnt = calc(p, R) - calc(p, L - 1)\n val newRet = ret * power((1L << p) % M, cnt, M) % M\n g(p + 1, newRet)\n }\n\n g(0, 1L)\n }\n\n queries.map(qry => {\n val L = findPos(qry.head + 1)\n val R = findPos(qry(1) + 1)\n if (L._1 == R._1) gao1(L._1, L._2, R._2, qry(2).toInt).toInt\n else {\n val t = gao1(L._1, L._2, 1000000000, qry(2).toInt) * gao1(R._1, 1, R._2, qry(2).toInt) % qry(2)\n (t * gao2(L._1 + 1, R._1 - 1, qry(2).toInt) % qry(2)).toInt\n }\n })\n }\n}\n``` | 0 | 0 | ['Scala'] | 0 |
find-products-of-elements-of-big-array | Beats 100% in Time and Memory | Bit Manipulation | Binary Search | Java | beats-100-in-time-and-memory-bit-manipul-0okb | \n\n\n# Complexity\n- Time complexity:\nEach query will be answered in O(log(n))\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\n\n long MAAAX = | alone18 | NORMAL | 2024-05-12T16:47:21.424780+00:00 | 2024-05-12T16:47:21.424805+00:00 | 77 | false | \n\n\n# Complexity\n- Time complexity:\nEach query will be answered in $$O(log(n))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n\n long MAAAX = 1000000000000000L;\n\n // this fn counts sum of powers of 2 in multiplication of powerful arrays from 0 to (2^n -1)\n long getMult(int n) {\n if (n <= 0)\n return 0L;\n\n long tmp = ((long) n * (n + 1)) / 2L;\n\n long pp = (long) Math.pow(2, n);\n\n return pp * tmp;\n }\n\n // this fn counts len of big_nums if we concate powerful arrays from 0 to (2^n -1)\n long getLen(int n) {\n long pp = (long) Math.pow(2, n - 1);\n return pp * (long) n;\n }\n\n // counts total sum of power of 2 and total on bits in n\n int[] getMaxSum(long n) {\n int tot = 0;\n int on = 0;\n\n for (int i = 0; i < 64; i++) {\n boolean x = (n & 1) == 1;\n n = n >> 1;\n\n if (x) {\n tot += i;\n on++;\n }\n\n }\n\n return new int[] { tot, on };\n }\n\n // counts sum of power of 2 for big_nums array of 0 to n\n long countMult(long n) {\n int[] maxSum = getMaxSum(n);\n int totSum = maxSum[0];\n\n long multB = (long) totSum;\n\n for (int i = 0; i < 64; i++) {\n\n boolean x = (n & 1) == 1;\n n = n >> 1;\n\n if (x) {\n totSum -= i;\n\n long tmp1 = (long) Math.pow(2, i);\n long tmp2 = (long)totSum * tmp1;\n long tmp3 = getMult(i - 1);\n long tmp4 = tmp2 + tmp3;\n\n\n multB += tmp4;\n }\n\n }\n\n return multB;\n }\n\n // counts len of big_nums array of 0 to n\n long countLen(long n) {\n int[] maxSum = getMaxSum(n);\n int totOn = maxSum[1];\n\n long onBits = (long) totOn;\n\n for (int i = 0; i < 64; i++) {\n\n boolean x = (n & 1) == 1;\n n = n >> 1;\n\n if (x) {\n totOn -= 1;\n\n long tmp1 = (long) Math.pow(2, i);\n long onTmp2 = (long)totOn * tmp1;\n long onTmp3 = getLen(i);\n long onTmp4 = onTmp2 + onTmp3;\n\n onBits += onTmp4;\n }\n\n }\n\n return onBits;\n }\n\n // find max n for which big_array(0 to n) length is equal or just smaller than target\n long bs(long target) {\n long l = 0L, r = MAAAX;\n\n while (l < r) {\n long mid = (l + r + 1) / 2L;\n\n long len = countLen(mid);\n\n if (len > target) {\n r = mid - 1;\n } else {\n l = mid;\n }\n\n }\n\n long finalLen = countLen(l);\n long finalMult = countMult(l);\n\n if (finalLen == target)\n return finalMult;\n\n // add remaining power of 2 from next number if len < target\n long nn = l + 1L;\n for (int i = 0; i < 64; i++) {\n boolean x = (nn & 1) == 1;\n nn = nn >> 1;\n\n if (x) {\n finalMult += (long) i;\n finalLen += 1L;\n }\n\n if (finalLen == target)\n return finalMult;\n }\n\n return -1;\n }\n\n // modular power of 2 with mod p\n long power(long x, long y, long p) {\n\n if(y == 0L) return 1L%p;\n\n long res = 1L;\n\n x = x % p;\n\n if (x == 0L)\n return 0L;\n\n while (y > 0L) {\n\n if ((y & 1) != 0L)\n res = (res * x) % p;\n\n y = y >> 1;\n x = (x * x) % p;\n }\n\n return res;\n }\n\n public int[] findProductsOfElements(long[][] queries) {\n\n \n int[] ans = new int[queries.length];\n\n\n for(int i=0; i<queries.length; i++)\n {\n long mult1 = bs(queries[i][0]);\n long mult2 = bs(queries[i][1]+1);\n\n ans[i] = (int)(power(2L,mult2-mult1,queries[i][2]));\n\n System.out.println(mult1+":"+mult2+":"+ans[i]);\n\n }\n\n return ans;\n\n }\n}\n``` | 0 | 0 | ['Binary Search', 'Bit Manipulation', 'Java'] | 0 |
find-products-of-elements-of-big-array | Bit Manipulation + Binary Search + Cyclic Property Of Bits | 65 ms | bit-manipulation-binary-search-cyclic-pr-ar3f | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | looneyd_noob | NORMAL | 2024-05-12T15:28:58.264301+00:00 | 2024-05-12T15:29:36.518552+00:00 | 61 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(q * log(1e15))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(q)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long bin_exp(long long a, long long b, long long mod){\n long long res = 1;\n while(b){\n if(b & 1){\n res = (res * a) % mod;\n }\n a = (a * a) % mod;\n b >>= 1;\n }\n return res;\n }\n unsigned long long f(long long num, int i){\n // returns the count of i-th bit set in range [0...num]\n // based on the cyclic property of bits\n unsigned long long a = (num + 1) / (1LL << (i+1));\n a = a * (1LL << i);\n long long excess = ((num + 1) % (1LL << (i+1))) - (1LL << i);\n return a + max(excess, 0LL);\n }\n unsigned long long g(long long num){\n unsigned long long sum = 0;\n for(int i=0; i<63; i++){\n unsigned long long t = f(num, i);\n sum += t;\n }\n return sum;\n }\n unsigned long long g_bit(long long num){\n unsigned long long sum = 0;\n for(int i=0; i<63; i++){\n unsigned long long t = f(num, i);\n sum += t * i;\n }\n return sum;\n }\n long long binary_search(long long k){\n long long low = 1, high = 1e15;\n while(low <= high){\n long long mid = low + ((high - low) >> 1);\n unsigned long long set_bits = g(mid);\n if(set_bits >= k){\n high = mid - 1;\n }else{\n low = mid + 1;\n }\n }\n return low;\n }\n vector<int> findProductsOfElements(vector<vector<long long>>& queries) {\n int q = queries.size();\n vector<int> v;\n for(auto& query: queries){\n long long lb = query[0]+1, ub = query[1]+1, mod = query[2];\n long long lb_num = binary_search(lb), ub_num = binary_search(ub);\n\n unsigned long long diff1 = lb - g(lb_num-1);\n unsigned long long diff2 = ub - g(ub_num-1);\n\n if(lb_num == ub_num){\n long long c = 0;\n unsigned long long ans = 1;\n for(int i=0; i<63; i++){\n if(lb_num & (1LL << i)){\n c++;\n if(c>=diff1 && c<=diff2){\n ans = ans * (1LL << i);\n ans %= mod;\n }\n }\n }\n v.push_back(ans);\n continue;\n }\n\n unsigned long long mid_part_sum = max(0ULL, g_bit(ub_num-1) - g_bit(lb_num));\n\n unsigned long long mid_part = bin_exp(2, mid_part_sum, mod);\n\n unsigned long long excess = 1;\n // for left part which is uneven\n int a = 0;\n for(int i=0; i<63; i++){\n if(lb_num & (1LL << i)){\n a++;\n if(a >= diff1){\n excess = excess * (1LL << i);\n excess %= mod;\n }\n }\n }\n // for right part which is uneven\n int b = 0;\n for(int i=0; i<63; i++){\n if(ub_num & (1LL << i)){\n b++;\n if(b <= diff2){\n excess = excess * (1LL << i);\n excess %= mod;\n }\n }\n }\n unsigned long long ans = (mid_part * excess) % mod;\n v.push_back(ans);\n }\n return v;\n }\n};\n``` | 0 | 0 | ['Binary Search', 'Bit Manipulation', 'C++'] | 0 |
find-products-of-elements-of-big-array | Bit manipulation, beats 100% at the time of writing | bit-manipulation-beats-100-at-the-time-o-5vog | Intuition\n\nEach number in the big_nums is a power of two. Since the answer is the product modulo some given number it is more convenient to work with exponent | vilmos_prokaj | NORMAL | 2024-05-12T03:46:11.203740+00:00 | 2024-05-12T03:46:11.203758+00:00 | 36 | false | # Intuition\n\nEach number in the `big_nums` is a power of two. Since the answer is the product modulo some given number it is more convenient to work with exponents, that is with the non-zero bit positions.\n\nThe naive solution is the following:\n```python\ndef bit_pos():\n n = 0\n while True:\n n0 = n\n while n0 > 0:\n bit = n0 & (-n0)\n n0 ^= bit\n yield bit.bit_length()-1\n n += 1\n\n\ndef naive(lo, hi, modulo):\n return pow(2, sum(itertools.islice(bit_pos(), lo, hi+1)), modulo)\n```\n\nWhat it does is the following: `bit_pos` is an infinite generator that produces the sequences of exponents (`bit.bit_length()-1`). Then the function `naive` accumulates the exponents in the given range and takes the power of two mod `modulo`.\n\nThe optimized version first computes $k$ such that the first $n$ element of the `big_nums` are coming from the integers `1,...,k` and not all bits of $k$ are used.\nUsing $k$ it is easy to find the sum of exponents of the first $n$ elements in `big_nums`.\n\n\n# Code\n```\ndef efficient(lo, hi, modulo):\n return pow(2, bigarray_prefixsum(hi+1)-bigarray_prefixsum(lo), modulo)\n\n\ndef bitcount_inv(n):\n """Returns k such that \n bit_count(k) <= n < bit_count(k) + k.bit_count() \n """\n lo = 0\n hi = 1 << 46\n while lo < hi:\n med = (lo+hi+1)//2\n if bit_count(med) <= n:\n lo = med\n else:\n hi = med-1\n return lo\n\ndef bigarray_prefixsum(n):\n """Computes\n sum(itertools.islice(bit_pos(), n))\n efficiently\n """\n k = bitcount_inv(n)\n total = bitpos_sum(k)\n n0 = n-bit_count(k)\n while n0 > 0:\n bit = k & (-k)\n n0 -= 1\n k ^= bit\n total += bit.bit_length()-1\n return total\n\ndef bit_count(n):\n """\n computes:\n ```\n def count(n):\n total = 0\n for k in range(n):\n total += k.bit_count()\n return total\n ``` \n efficiently\n """\n total = 0\n total_bits = n.bit_count()\n while n > 0:\n bit = n & (-n)\n n -= bit\n bit_pos = bit.bit_length()-1\n total_bits -= 1\n total += total_bits << bit_pos\n if bit_pos > 0:\n total += bit_pos << (bit_pos-1)\n return total\n\n\ndef bitpos_sum(n):\n """Computes:\n ```\n def count(n):\n total = 0\n for k in range(n):\n while k > 0:\n bit = k & (-k)\n k ^= bit\n total += bit.bit_length()-1\n return total\n ```\n efficiently\n """\n n0 = n\n bit_pos_sum = 0\n while n0 > 0:\n bit = n0 & (-n0)\n n0 ^= bit\n bit_pos_sum += bit.bit_length()-1\n \n total = 0\n while n > 0:\n bit = n & (-n)\n n ^= bit\n bit_pos = bit.bit_length()-1\n bit_pos_sum -= bit_pos\n total += (bit_pos_sum << bit_pos) \n if bit_pos > 1: \n total += (bit_pos*(bit_pos-1)) << (bit_pos-2) \n return total\n\nclass Solution:\n def findProductsOfElements(self, queries: List[List[int]]) -> List[int]:\n return [efficient(lo, hi, modulo) for lo, hi, modulo in queries]\n``` | 0 | 0 | ['Python3'] | 0 |
find-products-of-elements-of-big-array | My Solutions | my-solutions-by-hope_ma-k6fx | 1. Use the binary search\n\n/**\n * Time Complexity: O(n * log(bound) * log(bound))\n * Space Complexity: O(1)\n * where `n` is the length of the vector `querie | hope_ma | NORMAL | 2024-05-12T02:12:59.430912+00:00 | 2024-05-15T00:43:21.124065+00:00 | 11 | false | **1. Use the binary search**\n```\n/**\n * Time Complexity: O(n * log(bound) * log(bound))\n * Space Complexity: O(1)\n * where `n` is the length of the vector `queries`\n * `bound` is the maximum value of the `from`s and the `to`s of all queries `queries`\n */\nclass Solution {\n public:\n vector<int> findProductsOfElements(const vector<vector<long long>> &queries) {\n constexpr int lower_i = 0;\n constexpr int upper_i = 1;\n constexpr int mod_i = 2;\n const int n = static_cast<int>(queries.size());\n vector<int> ret(n);\n for (int i = 0; i < n; ++i) {\n const long long lower = queries[i][lower_i] + 1;\n const long long upper = queries[i][upper_i] + 1;\n const int mod = static_cast<int>(queries[i][mod_i]);\n \n const auto [lower_num, lower_bit] = get_stats(lower);\n const auto [upper_num, upper_bit] = get_stats(upper);\n if (lower_num == upper_num) {\n ret[i] = multiply_bits(lower_num, lower_bit, upper_bit, mod);\n } else {\n ret[i] = multiply_bits(lower_num, lower_bit, numeric_limits<int>::max(), mod);\n for (int bit = 0; (upper_num >> bit) > 0; ++bit) {\n ret[i] = static_cast<int>(static_cast<long long>(ret[i]) * power(1LL << bit, count_bit(bit, upper_num - 1) - count_bit(bit, lower_num), mod) % mod);\n }\n ret[i] = static_cast<int>(static_cast<long long>(ret[i]) * multiply_bits(upper_num, 1, upper_bit, mod) % mod);\n }\n }\n return ret;\n }\n \n private:\n long long count_bit(const int bit, const long long upper) {\n const long long half = 1LL << bit;\n const long long whole = half << 1;\n return (upper / whole) * half + max(0LL, upper % whole - (half - 1));\n }\n \n long long count_bits(const long long upper) {\n long long ret = 0;\n for (int bit = 0; (upper >> bit) > 0; ++bit) {\n ret += count_bit(bit, upper);\n }\n return ret;\n }\n \n pair<long long, int> get_stats(const long long length) {\n long long low = 1;\n long long high = length;\n while (low < high) {\n const long long mid = low + ((high - low) >> 1);\n if (count_bits(mid) < length) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return make_pair(high, length - count_bits(high - 1));\n }\n \n int multiply_bits(const long long number, const int lower_bit, const int upper_bit, const int mod) {\n int ret = 1;\n for (long long bit_value, bit = 1, num = number; num > 0; num -= bit_value, ++bit) {\n bit_value = num & -num;\n if (bit >= lower_bit && bit <= upper_bit) {\n ret = static_cast<int>(ret * bit_value % mod);\n }\n }\n return ret;\n }\n \n int power(const long long number, const long long pow, const int mod) {\n int ret = 1;\n int base = static_cast<int>(number % mod);\n for (long long p = pow; p > 0; p >>= 1) {\n if ((p & 0b1) == 0b1) {\n ret = static_cast<int>((static_cast<long long>(ret) * base) % mod);\n }\n base = static_cast<int>(static_cast<long long>(base) * base % mod);\n }\n return ret;\n }\n};\n```\n**2. Try every bit**\n```\n/**\n * let `p(number)` = [`p1`, `p2`, `p3`, ...] such that `number` = (2 ^ `p1`) + (2 ^ `p2`) + (2 ^ `p3`) + ...\n * p(0) = []\n * p(1) = [0]\n * p(2) = [1]\n * p(3) = [0, 1]\n * p(4) = [2]\n * p(5) = [0, 2]\n * p(6) = [1, 2]\n * p(7) = [0, 1, 2]\n * p(8) = [3]\n * p(9) = [0, 3]\n * p(10) = [1, 3]\n * ...\n *\n * let count(i) = len(p(0)) + len(p(1)) + ... + len(p((2 ^ i) - 1))\n * count(0) = len(p(0)) = 0\n * count(1) = len(p(0)) + len(p(1)) = 1\n * count(2) = len(p(0)) + len(p(1)) + len(p(2)) + len(p(3)) = 4\n * ...\n * count(n) = 2 * count(n - 1) + 2 ^ (n - 1)\n * count(n) = n * (2 ^ (n - 1))\n *\n * let p_sum(i) = sum(p(0)) + sum(p(1)) + ... + sum(p((2 ^ i) - 1))\n * let p_sum(0) = 0\n * p_sum(1) = sum(p(0)) + sum(p(1)) = 0\n * p_sum(2) = sum(p(0)) + sum(p(1)) + sum(p(2)) + sum(p(3)) = 2\n * ...\n * p_sum(n) = 2 * p_sum(n - 1) + (2 ^ (n - 1)) * (n - 1)\n * p_sum(n) = n * (n - 1) * (2 ^ (n - 2))\n *\n * Time Complexity: O(n * log(bound))\n * Space Complexity: O(1)\n * where `n` is the length of the vector `queries`\n * `bound` is the maximum value of the `from`s and the `to`s of all queries `queries`\n */\nclass Solution {\n public:\n vector<int> findProductsOfElements(const vector<vector<long long>> &queries) {\n constexpr int from_i = 0;\n constexpr int to_i = 1;\n constexpr int mod_i = 2;\n const int n = static_cast<int>(queries.size());\n vector<int> ret(n);\n for (int i = 0; i < n; ++i) {\n const long long from = queries[i][from_i];\n const long long to = queries[i][to_i] + 1;\n const int mod = static_cast<int>(queries[i][mod_i]);\n ret[i] = power(get_power_sum(to) - get_power_sum(from), mod);\n }\n return ret;\n }\n \n private:\n long long get_power_sum(const long long q) {\n const int most_bit = get_most_bit(q);\n long long n = 0LL;\n long long remains = q;\n long long ret = 0LL;\n for (int count_one = 0, sum_p = 0, bit = most_bit; remains > 0 && bit > -1; --bit) {\n const long long count = count_one * (1LL << bit) + (bit > 0 ? static_cast<long long>(bit) << (bit - 1) : 0);\n if (count > remains) {\n continue;\n }\n n |= 1LL << bit;\n remains -= count;\n ret += sum_p * (1LL << bit) + (bit > 1 ? ((static_cast<long long>(bit) * (bit - 1)) << (bit - 2)) : 0);\n ++count_one;\n sum_p += bit;\n }\n \n for (int bit = 0; bit < most_bit + 1 && remains > 0; ++bit) {\n if (((n >> bit) & 0b1) == 0b1) {\n ret += bit;\n --remains;\n }\n }\n return ret;\n }\n \n int get_most_bit(const long long q) {\n int ret = 0;\n for (long long num = q; num > 0; num >>= 1) {\n ++ret;\n }\n return ret - 1;\n }\n \n int power(const long long pow, const int mod) {\n int ret = 1;\n int base = 2;\n for (long long p = pow; p > 0; p >>= 1) {\n if ((p & 0b1) == 0b1) {\n ret = static_cast<int>(static_cast<long long>(ret) * base % mod);\n }\n base = static_cast<int>(static_cast<long long>(base) * base % mod);\n }\n return ret % mod;\n }\n};\n``` | 0 | 0 | [] | 0 |
find-products-of-elements-of-big-array | Short sol | short-sol-by-jwseph-obwr | Complexity\n- Time complexity: O(q\log^2 m) \n- Space complexity: O(q)\n\n# Explanation\n- Read this explanation: https://leetcode.com/problems/find-products-of | jwseph | NORMAL | 2024-05-11T21:19:30.007427+00:00 | 2024-05-11T21:23:39.536842+00:00 | 38 | false | # Complexity\n- Time complexity: $$O(q\\log^2 m)$$ \n- Space complexity: $$O(q)$$\n\n# Explanation\n- Read this explanation: https://leetcode.com/problems/find-products-of-elements-of-big-array/solutions/5143875/python-3-bisearch-count-1-s-and-accumulate-0-s/\n\n# Code\n```py\nclass Solution:\n def findProductsOfElements(self, queries: List[List[int]]) -> List[int]:\n def cnt(x, k):\n w = 1<<k+1\n return (x-x%w)//2 + max(x%w-w//2, 0)\n def count(x):\n return sum(cnt(x, k) for k in range(x.bit_length()))\n def sol(n):\n x = bisect_right(range(0, n+5), n, key=count)-1\n res = sum(k*cnt(x, k) for k in range(x.bit_length()))\n for _ in range(n-count(x)):\n res += (x&-x).bit_length()-1\n x &= x-1\n return res\n return [pow(2, sol(r+1)-sol(l), mod) for l, r, mod in queries]\n``` | 0 | 0 | ['Binary Search', 'Python3'] | 0 |
find-products-of-elements-of-big-array | JS Solution - Binary search | js-solution-binary-search-by-cutetn-qdis | Pro tip: Big heart for lil Xie \uD83D\uDC9C\uD83D\uDC9C\uD83D\uDC9C\n\n# Complexity\n- let n = queries.length, m = max(queries[*][1])\n- Time complexity: O(nlog | CuteTN | NORMAL | 2024-05-11T19:17:56.704256+00:00 | 2024-05-11T19:17:56.704294+00:00 | 26 | false | Pro tip: Big heart for lil Xie \uD83D\uDC9C\uD83D\uDC9C\uD83D\uDC9C\n\n# Complexity\n- let `n = queries.length`, `m = max(queries[*][1])`\n- Time complexity: $$O(nlogm)$$\n- Space complexity: $$O(n + m)$$\n\n# Code\n```js\nfunction quickPow(a, b, m) {\n if (b === 0) return 1;\n let t = quickPow(a, Math.floor(b / 2), m);\n t = (t * t) % m;\n if (b % 2) t = (t * a) % m;\n return t;\n}\n\nconst pcL = Array(50).fill(0);\nconst pcR = Array(50).fill(0);\nconst temps = Array(50).fill(0);\n\n/**\n * @param {number} maxCnt\n * @param {number[]} pows\n */\nfunction cntPows(maxCnt, pows) {\n let resNum = 0;\n let resCnt = 0;\n\n let l = 0;\n let r = 1e15;\n\n while (l <= r) {\n temps.fill(0);\n let m = Math.floor((l + r) / 2);\n let p = 1;\n let c = 0;\n let t = m;\n\n for (let i = 0; t; i++, p *= 2) {\n let cb = 0;\n if (t % 2) {\n cb = (m % p) + 1;\n }\n\n t = Math.floor(t / 2);\n cb += t * p;\n\n c += cb;\n if (c > maxCnt) break;\n temps[i] = cb;\n }\n\n if (c > maxCnt) {\n r = m - 1;\n } else {\n l = m + 1;\n resNum = m;\n resCnt = c;\n for (let i = 0; i < 50; ++i) {\n pows[i] = temps[i];\n }\n }\n }\n\n ++resNum;\n for (let i = 0; resCnt < maxCnt; ++i) {\n if (resNum % 2) {\n ++pows[i];\n ++resCnt;\n }\n resNum = Math.floor(resNum / 2);\n }\n}\n\n/**\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar findProductsOfElements = function (queries) {\n let n = queries.length;\n let res = new Uint32Array(n);\n\n for (let i = 0; i < n; ++i) {\n let [l, r, m] = queries[i];\n ++r;\n cntPows(l, pcL);\n cntPows(r, pcR);\n let cur = 1;\n let p = 1;\n\n for (let j = 0; j < 50; ++j, p = (p * 2) % m) {\n cur = (cur * quickPow(p, pcR[j] - pcL[j], m)) % m;\n }\n res[i] = cur;\n }\n\n return res;\n};\n``` | 0 | 0 | ['Binary Search', 'JavaScript'] | 0 |
find-products-of-elements-of-big-array | Binary Search Solution | C++ | 200ms | binary-search-solution-c-200ms-by-shrana-rtjn | Binary search solution\n# Code\n\nclass Solution {\npublic:\n long long countOnes(long long x, long long cycle, long long pow2Is) {\n if (x < 0) {\n | shrana_ak | NORMAL | 2024-05-11T18:44:35.303834+00:00 | 2024-05-11T18:44:35.303874+00:00 | 79 | false | Binary search solution\n# Code\n```\nclass Solution {\npublic:\n long long countOnes(long long x, long long cycle, long long pow2Is) {\n if (x < 0) {\n return 0;\n }\n long long totCycle = x / cycle;\n long long ones = (totCycle * pow2Is);\n long long left = x % cycle;\n left++;\n left -= pow2Is;\n return ones + max(0ll, left);\n }\n\n long long power(long long a, long long b, long long mod) {\n long long ans = 1;\n a = a % mod;\n while (b) {\n if (b % 2) {\n ans = (ans * a) % mod;\n }\n b = b / 2;\n\n a = (a * a) % mod;\n }\n return ans;\n }\n\n vector<long long> computeVec(long long x) {\n long long s = 0, e = 1000000000000000ll, numOfOnes = 0, num = 0;\n vector<long long> freq(61, 0);\n while (s <= e) {\n long long mid = (s + e) / 2;\n long long ones = 0;\n vector<long long> f(61, 0);\n for (int j = 0; j <= 60; j++) {\n long long pow2Is = (1ll << j);\n long long cycle = (1ll << (j + 1));\n long long o = countOnes(mid, cycle, pow2Is);\n ones += o;\n f[j] = o;\n }\n if (ones <= x) {\n numOfOnes = ones;\n num = mid;\n for (int i = 0; i <= 55; i++) {\n freq[i] = f[i];\n }\n s = mid + 1;\n } else {\n e = mid - 1;\n }\n }\n if (numOfOnes < x) {\n long long left = x - numOfOnes;\n long long number = num + 1;\n long long int index = 0;\n while (left and index < 60) {\n if (number & (1ll << index)) {\n left--;\n freq[index]++;\n }\n index++;\n }\n }\n\n return freq;\n }\n\n long long compute(long long x, long long y, long long mod) {\n x = max(0ll, x);\n vector<long long> f1 = computeVec(y);\n vector<long long> freq = computeVec(x);\n long long ans = 1;\n for (int j = 0; j <= 55; j++) {\n long long pow2Is = (1ll << j);\n long long cycle = (1ll << (j + 1));\n long long o = f1[j] - freq[j];\n ans = (ans * power(pow2Is, o, mod)) % mod;\n }\n return ans;\n }\n vector<int> findProductsOfElements(vector<vector<long long>>& queries) {\n vector<int> ans;\n for (auto i : queries) {\n long long x = i[0];\n long long y = i[1];\n long long mod = i[2];\n long long add = compute(x, y + 1, mod) % mod;\n ans.push_back(add);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Binary Search', 'C++'] | 0 |
find-products-of-elements-of-big-array | Solution | solution-by-penrosecat-ikz2 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe array only has elements corresponding to set bits in numbers. To find the index in | penrosecat | NORMAL | 2024-05-11T18:36:13.034831+00:00 | 2024-05-11T18:36:13.034858+00:00 | 22 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe array only has elements corresponding to set bits in numbers. To find the index in the big array, we need the sum of set bits upto n. \n\nTo find the final product we also need the position wise bit frequency upto (from-1) and (to) then we can use the difference to calculate the final product.\n\nFor any number n, these can be found with the following\n\n```\nfor(int i = 0; i<len; i++)\n{\n long long period = 1LL << (i+1);\n long long pos = period/2;\n \n sumsetbts[i] = (n/period)*(1LL << i) + max(0LL, n%period - pos + 1LL);\n}\n```\n\nTo find from and to, a binary search on the range 1 to 10^15 we can find the integer which has a sum of set bits (count of elements) <= some value including all the set bits upto its own representation.\n\nWe will take "some value" as from and to+1, because there is a count of from elements appearing before index from and to+1 elements appearing before and including index to, so the difference will keep [from..to] inclusive.\n\nNow the binary search result will only give us a number upto which the sum of set bits is <= the desired count. To get the desired count, we have to add bits from lsb to msb from the next number after the solution of binary search.\n\nCheck whether bits are set:\n\n```\nfor(int i = 0; i<60; i++)\n{\n if(((n+1) >> i)&1)\n {\n a[i]++;\n sum++;\n }\n}\n```\n\nAlso needs modular exponentiation to calculate the final product.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // 1 2 1 2 4 1 4 2 4\n const int len = 60;\n const long long mx = 1e15 + 10;\n \n long long modexp(long long a, long long b, long long mod)\n {\n a %= mod;\n long long ans = 1;\n while(b > 0)\n {\n if(b%2)\n {\n ans = (ans*a)%mod;\n }\n \n a = (a*a)%mod;\n b /= 2;\n }\n \n return ans;\n }\n \n vector<long long> sumofsetbitsupto(long long n)\n {\n vector<long long> ans(len, 0);\n\n for(int i = 0; i<len; i++)\n {\n long long period = 1LL << (i+1);\n long long pos = period/2;\n \n ans[i] = (n/period)*(1LL << i) + max(0LL, n%period - pos + 1LL);\n }\n\n return ans;\n }\n \n long long ssum(vector<long long>& a)\n {\n long long sum = 0;\n for(int i = 0; i<a.size(); i++)\n {\n sum += a[i];\n }\n return sum;\n }\n \n long long getnumberjustbeforepos(long long pos)\n {\n long long lo = 1;\n long long hi = mx;\n long long ans = -1;\n \n while(lo <= hi)\n {\n long long mid = lo + (hi - lo)/2;\n vector<long long> a = sumofsetbitsupto(mid);\n\n if(ssum(a) <= pos)\n {\n ans = mid;\n lo = mid+1;\n }\n else\n {\n hi = mid-1;\n }\n }\n \n return ans;\n }\n\n vector<long long> getfreqbeforepos(long long n, long long pos)\n {\n vector<long long> a = sumofsetbitsupto(n);\n long long sum = ssum(a);\n\n if(sum < pos)\n {\n for (int i = 0; i<len; i++)\n {\n if(sum == pos)\n {\n break;\n }\n\n if(((n+1) >> i)&1)\n {\n a[i]++;\n sum++;\n }\n }\n }\n\n return a;\n }\n \n vector<int> findProductsOfElements(vector<vector<long long>>& queries) {\n //[1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...]\n //[0, 1, 0, 1, 2, 0, 2, 1, 2, 0, 1, 2, 3]\n \n // to find index associated with certain actual number, need the sum of set bits for all numbers 1 to n-1\n \n // sum of set bits for bit pos i = n/(1 << i+1) + max(0, n%(1<<(i+1)) - 1<<i + 1)\n vector<int> ans(queries.size());\n \n for(int i = 0; i<queries.size(); i++)\n {\n long long from = queries[i][0];\n long long to = queries[i][1];\n long long mod = queries[i][2];\n \n vector<long long> fpos_prefix = getfreqbeforepos(getnumberjustbeforepos(from), from);\n vector<long long> tpos_prefix = getfreqbeforepos(getnumberjustbeforepos(to+1), to+1);\n\n vector<long long> diff(len, 0);\n \n for(int i = 0; i<len; i++)\n {\n diff[i] = tpos_prefix[i] - fpos_prefix[i];\n }\n \n long long product = 1;\n \n for(int i = 0; i<len; i++)\n {\n long long p = (1LL << i);\n product = (product * modexp(p, diff[i], mod))%mod;\n }\n \n ans[i] = (int)product;\n }\n \n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | 🔥Simple Count of coloured row/column Detailed Solution | simple-map-count-detailed-solution-by-su-qxhh | 🧠 IntuitionThe task requires finding the smallest index in arr where a row or column in the matrix mat becomes completely painted. The key idea is:
Use a hash m | Sumeet_Sharma-1 | NORMAL | 2025-01-20T01:22:28.822119+00:00 | 2025-01-20T02:33:24.565714+00:00 | 19,462 | false | # 🧠 Intuition
The task requires finding the smallest index in `arr` where a row or column in the matrix `mat` becomes completely painted. The key idea is:
- Use a hash map to quickly locate the `(row, column)` of any number in `mat`.
- Maintain counts of uncolored cells for rows and columns.
- Stop processing as soon as any row or column's uncolored count becomes zero.
This ensures an efficient solution by minimizing redundant calculations.
---
# 🚀 Approach
### 1️⃣ **Mapping Cell Values to Indices**
- Traverse the matrix `mat` and store the position of each number as `(row, column)` in a hash map.
- **Reason**: This allows O(1) lookup for any number in `arr`.
### 2️⃣ **Tracking Uncolored Cells**
- Initialize two arrays:
- `rowCount`: An array of size `m` (number of rows), where each entry starts with `n` (number of columns).
- `colCount`: An array of size `n` (number of columns), where each entry starts with `m` (number of rows).
- These arrays track the remaining uncolored cells for each row and column.
### 3️⃣ **Processing the Painting Sequence**
- Iterate through `arr`:
- For each number:
- Use the hash map to get its position `(row, column)` in the matrix.
- Decrement the uncolored counts in `rowCount` and `colCount`.
- Check if either count becomes zero:
- If yes, return the current index as the result.
### 4️⃣ **Returning the Result**
- The logic ensures that a row or column will eventually be fully painted. If no row or column is found (unlikely with valid input), return `-1`.
---
# ⏱ Complexity
### Time Complexity:
- **Building the Hash Map**: $$O(m \times n)$$, where `m` is the number of rows and `n` is the number of columns in `mat`.
- **Processing `arr`**: $$O(k)$$, where `k` is the size of `arr`.
- **Overall**: $$O(m \times n + k)$$.
### Space Complexity:
- **Hash Map**: $$O(m \times n)$$ to store positions of all numbers in `mat`.
- **Row and Column Arrays**: $$O(m + n)$$.
- **Overall**: $$O(m \times n)$$.

---
# 💻 Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int rows = mat.size(), cols = mat[0].size();
unordered_map<int, pair<int, int>> positionMap;
vector<int> rowCount(rows, cols), colCount(cols, rows);
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
positionMap[mat[r][c]] = {r, c};
}
}
for (int idx = 0; idx < arr.size(); ++idx) {
int val = arr[idx];
auto [row, col] = positionMap[val];
if (--rowCount[row] == 0 || --colCount[col] == 0) {
return idx;
}
}
return -1;
}
};
```
```Java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int rows = mat.length, cols = mat[0].length;
Map<Integer, int[]> positionMap = new HashMap<>();
int[] rowCount = new int[rows];
int[] colCount = new int[cols];
Arrays.fill(rowCount, cols);
Arrays.fill(colCount, rows);
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
positionMap.put(mat[r][c], new int[]{r, c});
}
}
for (int idx = 0; idx < arr.length; ++idx) {
int[] pos = positionMap.get(arr[idx]);
if (--rowCount[pos[0]] == 0 || --colCount[pos[1]] == 0) {
return idx;
}
}
return -1;
}
}
```
```Python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
rows, cols = len(mat), len(mat[0])
position_map = {mat[r][c]: (r, c) for r in range(rows) for c in range(cols)}
row_count = [cols] * rows
col_count = [rows] * cols
for idx, val in enumerate(arr):
row, col = position_map[val]
row_count[row] -= 1
col_count[col] -= 1
if row_count[row] == 0 or col_count[col] == 0:
return idx
return -1
```
```C# []
public class Solution {
public int FirstCompleteIndex(int[] arr, int[][] mat) {
int rows = mat.Length, cols = mat[0].Length;
var positionMap = new Dictionary<int, (int, int)>();
int[] rowCount = new int[rows];
int[] colCount = new int[cols];
Array.Fill(rowCount, cols);
Array.Fill(colCount, rows);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
positionMap[mat[r][c]] = (r, c);
}
}
for (int idx = 0; idx < arr.Length; idx++) {
var (row, col) = positionMap[arr[idx]];
if (--rowCount[row] == 0 || --colCount[col] == 0) {
return idx;
}
}
return -1;
}
}
```
```JavaScript []
var firstCompleteIndex = function(arr, mat) {
const rows = mat.length, cols = mat[0].length;
const positionMap = new Map();
const rowCount = Array(rows).fill(cols);
const colCount = Array(cols).fill(rows);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
positionMap.set(mat[r][c], [r, c]);
}
}
for (let idx = 0; idx < arr.length; idx++) {
const [row, col] = positionMap.get(arr[idx]);
if (--rowCount[row] === 0 || --colCount[col] === 0) {
return idx;
}
}
return -1;
};
```
```Go []
func firstCompleteIndex(arr []int, mat [][]int) int {
rows, cols := len(mat), len(mat[0])
positionMap := make(map[int][2]int)
rowCount := make([]int, rows)
colCount := make([]int, cols)
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
positionMap[mat[i][j]] = [2]int{i, j}
}
}
for i := 0; i < rows; i++ {
rowCount[i] = cols
}
for i := 0; i < cols; i++ {
colCount[i] = rows
}
for idx, val := range arr {
row, col := positionMap[val][0], positionMap[val][1]
rowCount[row]--
colCount[col]--
if rowCount[row] == 0 || colCount[col] == 0 {
return idx
}
}
return -1
}
```
| 135 | 5 | ['Array', 'Hash Table', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#'] | 18 |
first-completely-painted-row-or-column | Explained - using map || Very simple and easy to understand solution | explained-using-map-very-simple-and-easy-ciwc | \n# Approach\nWe will have two map for tracking the row and col of a number, so that we can get the row,col in O(1) time.\nThen we have another two map ( mprc, | kreakEmp | NORMAL | 2023-04-30T04:18:30.142507+00:00 | 2023-04-30T09:02:11.773850+00:00 | 7,368 | false | \n# Approach\nWe will have two map for tracking the row and col of a number, so that we can get the row,col in O(1) time.\nThen we have another two map ( mprc, mpcc) which basically count the no. elements seen in that row and no. of elements seen in that column.\n\n1. Map the row, col of each of elements\n2. Travesrse the arr and keep updatinf row & col count \n3. Once the row count equal to max or col count equal to max return index\n\n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n unordered_map<int, int> mpr, mpc, mprc, mpcc;\n for(int i = 0; i < mat.size(); i++){\n for(int j = 0; j< mat[0].size(); ++j){\n mpr[mat[i][j]] = i; mpc[mat[i][j]] = j;\n }\n }\n for(int i = 0; i < arr.size(); i++){\n int n = arr[i];\n mprc[mpr[n]]++; mpcc[mpc[n]]++;\n if(mprc[mpr[n]] == mat[0].size() || mpcc[mpc[n]] == mat.size()) return i;\n }\n return -1;\n }\n};\n```\n\nSolution - 2: \nI find the following solution interesting by @Tushar_aherwar\n, with reverse mapping of the above solution: https://leetcode.com/problems/first-completely-painted-row-or-column/solutions/3469270/c-solution-space-complexity-o-n/?orderBy=most_votes\n\n<b>Here is an article of my recent interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted | 34 | 1 | ['C++'] | 9 |
first-completely-painted-row-or-column | 3 passes -> 2 passes||C++3ms Py3 99.05% | 3-passes-solution4ms-beats-9512-by-anwen-h592 | IntuitionUse vector in stead of a hash map.
3 passes
2nd solution is 2 passes which is much simpler. both C++ & Python are implemented.Approach
Declare vector i | anwendeng | NORMAL | 2025-01-20T00:42:25.361648+00:00 | 2025-01-20T02:42:15.696281+00:00 | 4,082 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Use vector in stead of a hash map.
3 passes
2nd solution is 2 passes which is much simpler. both C++ & Python are implemented.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Declare vector `idx(N+1)` where `N=m*n`
2. Use a loop to assign the values `idx[arr[i]]=i` for i
3. Need 2 correspondences for `pos=0,...,N-1` to its row index & its col index. So declare `to_i(N), to_j(N)`
4. In a double for loop assign the values
```
int pos=idx[mat[i][j]];
to_i[pos]=i;
to_j[pos]=j;
```
5. The 3rd pass is to find the answer. Declare `row(m), col(n)`.
6. Use a single loop to find the i:
```
int pos=idx[arr[i]];
// either row[..] or col[..] is full
if (++row[to_i[pos]]==n || ++col[to_j[pos]]==m)
return i;
```
7. 2nd approach is made which is much easier than 1st one. Just consider two mapping `to_i: mat[i][j] -> i & to_j: mat[i][j]-> j`
8. Python code is implemented.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(mn)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(mn)$$
# Code ||C++ 3 passes 4ms beats 95.12%
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
const int m=mat.size(), n=mat[0].size(), N=m*n;
vector<int> idx(N+1);
for(int i=0; i<N; i++)
idx[arr[i]]=i;
vector<int> to_i(N), to_j(N);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int pos=idx[mat[i][j]];
to_i[pos]=i;
to_j[pos]=j;
}
}
vector<int> row(m), col(n);
for(int i=0; i<N; i++){
int pos=idx[arr[i]];
if (++row[to_i[pos]]==n || ++col[to_j[pos]]==m) return i;
}
return -1;
}
};
```
# 2 passes||C++ 3ms Beats 97.87%| Python 64ms beats 99.05%
```C++ []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
const int m=mat.size(), n=mat[0].size(), N=m*n;
vector<int> to_i(N+1), to_j(N+1);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int x=mat[i][j];
to_i[x]=i;
to_j[x]=j;
}
}
vector<int> row(m), col(n);
for(int i=0; i<N; i++){
int x=arr[i];
if (++row[to_i[x]]==n || ++col[to_j[x]]==m) return i;
}
return -1;
}
};
```
```Python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n=len(mat), len(mat[0])
N=m*n
to_i=[-1]*(N+1)
to_j=[-1]*(N+1)
for i, row in enumerate(mat):
for j, x in enumerate(row):
to_i[x]=i
to_j[x]=j
R=[0]*m
C=[0]*n
for i, x in enumerate(arr):
R[to_i[x]]+=1
C[to_j[x]]+=1
if R[to_i[x]]==n or C[to_j[x]]==m:
return i
return -1
``` | 32 | 4 | ['Array', 'Matrix', 'C++', 'Python3'] | 11 |
first-completely-painted-row-or-column | Simple java solution | simple-java-solution-by-siddhant_1602-9k46 | Complexity\n- Time complexity: O(mn)\n\n- Space complexity: O(mn)\n\n# Code\n\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n | Siddhant_1602 | NORMAL | 2023-04-30T04:01:22.701517+00:00 | 2023-04-30T04:11:38.847036+00:00 | 2,387 | false | # Complexity\n- Time complexity: $$O(m*n)$$\n\n- Space complexity: $$O(m*n)$$\n\n# Code\n```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n Map<Integer, int[]> nm = new HashMap<>();\n int m=mat.length;\n int n=mat[0].length;\n for (int i=0;i<m;i++)\n {\n for (int j=0;j<n;j++)\n {\n nm.put(mat[i][j], new int[]{i, j});\n }\n }\n int a[]=new int[m];\n int b[]=new int[n];\n for (int i = 0; i < arr.length; i++)\n {\n int c[] = nm.get(arr[i]);\n a[c[0]]++;\n b[c[1]]++;\n if(a[c[0]]==n||b[c[1]]==m)\n {\n return i;\n }\n }\n return -1;\n }\n}\n``` | 26 | 1 | ['Hash Table', 'Java'] | 6 |
first-completely-painted-row-or-column | Beats 80.60% | Array | HashMap | Solution for LeetCode#2661 | array-hashmap-solution-for-leetcode2661-p3bcg | IntuitionThe problem requires us to find the first index in the given array arr where a complete row or column in the matrix mat is filled. We can keep track of | samir023041 | NORMAL | 2025-01-20T00:49:26.512617+00:00 | 2025-01-20T01:02:56.044239+00:00 | 3,736 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to find the first index in the given array arr where a complete row or column in the matrix mat is filled. We can keep track of the number of filled cells in each row and column, and return the index as soon as any row or column is completely filled.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Create two arrays rowFreq and colFreq to keep track of the number of filled cells in each row and column respectively.
2. Create a HashMap to store the position (row and column) of each element in the matrix.
3. Iterate through the arr array:
- For each element, get its position in the matrix from the HashMap.
- Increment the corresponding row and column frequencies.
- If any row frequency equals the number of columns or any column frequency equals the number of rows, return the current index.
4. If no complete row or column is found, return -1 (though this case should not occur given the problem constraints).
# Complexity
- Time complexity: O(m*n + k), where k is the size of arr
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(m⋅n + m + n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m=mat.length;
int n=mat[0].length;
//Declare array frequency for Row and Column
int[] rowFeq=new int[m];
int[] colFeq=new int[n];
//Set HashMap for the Matrix value corresponding row Index and column Index
Map<Integer, int[]> map=new HashMap<>();
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
map.put(mat[i][j], new int[]{i,j});
}
}
//Traversing the "arr", painting the "mat" cell and increasing the "rowFeq" and "colFeq"
for(int i=0; i<arr.length; i++){
int[] idx=map.get(arr[i]);
int r=idx[0];
int c=idx[1];
rowFeq[r]++;
colFeq[c]++;
//rowFeq[r] will be equal of no. of columns
//colFeq[c] will be equal of no. of rows
if(rowFeq[r]==n || colFeq[c]==m){
return i;
}
}
return -1;
}
}
```
```python []
class Solution(object):
def firstCompleteIndex(self, arr, mat):
"""
:type arr: List[int]
:type mat: List[List[int]]
:rtype: int
"""
m = len(mat)
n = len(mat[0])
# Declare array frequency for Row and Column
rowFeq = [0] * m
colFeq = [0] * n
# Set HashMap for the Matrix value corresponding row Index and column Index
map = {}
for i in range(m):
for j in range(n):
map[mat[i][j]] = [i, j]
# Traversing the "arr", painting the "mat" cell and increasing the "rowFeq" and "colFeq"
for i in range(len(arr)):
idx = map[arr[i]]
r = idx[0]
c = idx[1]
rowFeq[r] += 1
colFeq[c] += 1
# rowFeq[r] will be equal of no. of columns
# colFeq[c] will be equal of no. of rows
if rowFeq[r] == n or colFeq[c] == m:
return i
return -1
``` | 25 | 6 | ['Hash Table', 'Python', 'Java', 'Python3'] | 6 |
first-completely-painted-row-or-column | ✔💯 DAY 395 | EASY | 100% 0ms | [PYTHON/JAVA/C++] | EXPLAINED | Approach 💫 | day-395-easy-100-0ms-pythonjavac-explain-vz78 | Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n Describe your approach to solving the problem. \n##### \u | ManojKumarPatnaik | NORMAL | 2023-04-30T04:01:02.193646+00:00 | 2023-04-30T04:10:33.829332+00:00 | 1,800 | false | # Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tWe are given an array arr and a matrix mat.\n##### \u2022\tWe first create a HashMap called map to store the coordinates of each element in mat. The key of the HashMap is the value of the element, and the value is an array of two integers representing the row and column indices of the element.\n##### \u2022\tWe also create two arrays row and col to keep track of the number of elements painted in each row and column of mat.\n##### \u2022\tWe then iterate over the elements of arr and for each element, we get its coordinates from the map\n##### \u2022\tWe increment the count of painted elements in the row and column corresponding to the coordinates of the current element.\n##### \u2022\tWe then check if the count of painted elements in the row or column of the current element is equal to the length of the row or column, respectively. If either of these conditions is true, it means that the entire row or column has been painted, and we return the index of the current element.\n##### \u2022\tIf we have iterated over all the elements of arr and have not found any completely painted row or column, we return -1.\n##### \u2022\tThe intuition behind this approach is that we can keep track of the number of painted elements in each row and column of mat as we iterate over the elements of arr. If the count of painted elements in any row or column becomes equal to the length of the row or column, it means that the entire row or column has been painted, and we can return the index of the current element. If we have iterated over all the elements of arr and have not found any completely painted row or column, it means that there is no completely painted row or column in mat, and we return -1.\n\n\n\n\n# Complexity\n- Time complexity: o(n2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n int m= mat.length;\n int n = mat[0].length;\n HashMap<Integer,int[]> map = new HashMap<>();\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n map.put(mat[i][j],new int[]{i,j});\n int row[] = new int[m];\n int col[] = new int[n];\n for(int i=0;i<arr.length;i++){\n int x[] = map.get(arr[i]);\n row[x[0]]++;\n col[x[1]]++;\n if(row[x[0]]==n || col[x[1]]==m) return i; \n }\n return -1;\n }\n```\n\n```python []\ndef firstCompleteIndex(arr: List[int], mat: List[List[int]]) -> int:\n m = len(mat)\n n = len(mat[0])\n map = {}\n for i in range(m):\n for j in range(n):\n map[mat[i][j]] = [i, j]\n row = [0] * m\n col = [0] * n\n for i in range(len(arr)):\n x = map[arr[i]]\n row[x[0]] += 1\n col[x[1]] += 1\n if row[x[0]] == n or col[x[1]] == m:\n return i\n return -1\n```\n```c++ []\n#include <unordered_map>\n#include <vectorusing namespace std;\n\nint firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int m = mat.size();\n int n = mat[0].size();\n unordered_map<int, vector<int>> map;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n map[mat[i][j]] = {i, j};\n }\n }\n vector<int> row(m);\n vector<int> col(n);\n for (int i = 0; i < arr.size(); i++) {\n vector<int> x = map[arr[i]];\n row[x[0]]++;\n col[x[1]]++;\n if (row[x[0]] == n || col[x[1]] == m) {\n return i;\n }\n }\n return -1;\n}\n```\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n\n\n\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A | 24 | 2 | ['Python', 'C++', 'Java', 'Python3'] | 4 |
first-completely-painted-row-or-column | 0ms |Beats 100% Proof | Using Hash Mapping with Simulation| Efficient & Easy C++ Solu| Full Explain | 0ms-beats-100-proof-using-hash-mapping-w-99vz | IntuitionThe task requires us to determine the smallest index i in the array arr such that either a row or a column in the matrix mat becomes completely painted | HarshitSinha | NORMAL | 2025-01-20T02:31:27.577743+00:00 | 2025-01-20T02:31:27.577743+00:00 | 2,251 | false |

---
# Intuition
The task requires us to determine the smallest index `i` in the array `arr` such that either a row or a column in the matrix `mat` becomes completely painted.
- Each element in `arr` corresponds to a number in `mat` that gets painted in sequence.
- We can keep track of how many elements of each row and column are painted.
- The first time any row or column becomes fully painted, we return that index `i`.
<!-- Describe your first thoughts on how to solve this problem. -->
---
# Approach
**1. Mapping numbers in `mat` to their positions :**
Create mappings to quickly find the row and column indices of each number in the matrix. This avoids searching the matrix repeatedly.
- Use a `numToIndex` vector to map numbers from `mat` to their index in `arr`.
- Use `rowPos` and `colPos` arrays to store the row and column indices of each number in `mat`.
**2. Tracking painted cells :**
Maintain two arrays:
- `rowPainted` to track the number of painted cells in each row.
- `colPainted` to track the number of painted cells in each column.
**3. Simulating the painting process :**
Iterate through `arr`:
- For each number in `arr`, find its corresponding row and column indices using the mappings (`rowPos` and `colPos`).
- Increment the count for that row and column in `rowPainted` and `colPainted`.
- Check if the row or column is fully painted (count equals the number of cells in the row/column).
**4. Return the result :**
- The first index `i` where a row or column is completely painted is the answer.
<!-- Describe your approach to solving the problem. -->
---
# Complexity
- Time complexity: O(m⋅n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(m⋅n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
---

---
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size(), N = m * n;
vector<int> numToIndex(N + 1, -1);
for (int i = 0; i < N; ++i) {
numToIndex[arr[i]] = i;
}
vector<int> rowPainted(m, 0), colPainted(n, 0);
vector<int> rowPos(N), colPos(N);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int num = mat[i][j];
int indexInArr = numToIndex[num];
rowPos[indexInArr] = i;
colPos[indexInArr] = j;
}
}
for (int i = 0; i < N; ++i) {
int num = arr[i];
int rowIdx = rowPos[numToIndex[num]];
int colIdx = colPos[numToIndex[num]];
if (++rowPainted[rowIdx] == n || ++colPainted[colIdx] == m) {
return i;
}
}
return -1;
}
};
``` | 22 | 0 | ['Array', 'Hash Table', 'Greedy', 'Matrix', 'Simulation', 'C++'] | 6 |
first-completely-painted-row-or-column | C++ 🔥 DRY RUN 🔥 single map | c-dry-run-single-map-by-tusharaherwar3-fwox | \n\n# Code\n\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n\n unordered_map<int,int>mp;\n for(int | TusharAherwar3 | NORMAL | 2023-04-30T08:28:34.435492+00:00 | 2023-05-03T16:04:57.025429+00:00 | 1,144 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n\n unordered_map<int,int>mp;\n for(int i = 0; i < arr.size(); i++) {\n mp[arr[i]] = i;\n }\n\n int minIndex = INT_MAX , maxIndex = INT_MIN;\n int rowSize = mat.size();\n int colSize = mat[0].size();\n\n for(int row = 0; row < rowSize; row++) {\n maxIndex = INT_MIN;\n for(int column = 0; column < colSize; column++) {\n int indexVal = mp[mat[row][column]];\n maxIndex = max(maxIndex , indexVal);\n }\n minIndex = min(minIndex , maxIndex);\n }\n \n for(int column = 0; column < colSize; column++) {\n maxIndex = INT_MIN;\n for(int row = 0; row < rowSize; row++) {\n int indexVal2 = mp[mat[row][column]];\n maxIndex = max(maxIndex , indexVal2);\n }\n minIndex = min(minIndex , maxIndex);\n }\n return minIndex; \n}\n}; \n\n``` | 21 | 0 | ['C++'] | 4 |
first-completely-painted-row-or-column | C++ | Using Only Single Map | Explained | Easy to Understand | c-using-only-single-map-explained-easy-t-s9s0 | C++ Code\n\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n \n int n = size(mat), m = size(m | Rishabhsinghal12 | NORMAL | 2023-04-30T05:27:13.488506+00:00 | 2023-05-04T11:43:25.319984+00:00 | 2,224 | false | **C++ Code**\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n \n int n = size(mat), m = size(mat[0]), res = m*n;\n \n unordered_map<int,int> map;\n \n for(int i = 0; i < m*n; i++)map[arr[i]] = i;\n \n for(int i = 0; i < n; i++) {\n int maxIdx = 0;\n \n for(int j = 0; j < m; j++) {\n maxIdx = max(maxIdx, map[mat[i][j]]);\n }\n \n res = min(res,maxIdx);\n }\n \n for(int i = 0; i < m; i++) {\n int maxIdx = 0;\n \n for(int j = 0; j < n; j++) {\n maxIdx = max(maxIdx, map[mat[j][i]]);\n }\n \n res = min(res,maxIdx);\n }\n \n return res;\n \n }\n};\n```\n\n**Explanation**\n\n* unordered_map<int,int> map; - Here used to mark the order of arr items\n* First loop iterates by row, to identify by each row the index of last marked arr item. Then get the min, which row marked(finished) first:\n\n```\nfor(int i = 0; i < n; i++) {\n int maxIdx = 0;\n \n for(int j = 0; j < m; j++) {\n maxIdx = max(maxIdx, map[mat[i][j]]);\n }\n \n res = min(res,maxIdx);\n}\n```\n* Second loop iterates by column and makes the same logic as first loop described above.\n\n* Let\'s test in second example of the problem:\n```Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] Output: 3```\n\n* After mark the order of arr in map, we can draw second matrix that shows the mark position by arr:\n\n```\n[5,0,6],\n[4,3,7],\n[1,2,8]\n```\n\n* First loop iteration by row:\n\n```\n[5,0,6], // maxIdx = 6\n[4,3,7], // maxIdx = 7\n[1,2,8] // maxIdx = 8\n\nmin of these is `6`, we can see by row first finished first row, by arr item index `6`\n```\n\n* Second loop iteration by column:\n```\n[5,0,6], \n[4,3,7], \n[1,2,8] \n\nMax by col:\n5 3 8\n```\n\n* min of these(5,3,8) is 3, we can see by column first finished second column by arr item index 3. If we compare which one first finished by row or column, the answer is by column because arr value by index 3 becomes earlier than index 6\n\n*Thank you @Yerkon for explaining the code* | 14 | 1 | ['Hash Table', 'C', 'C++'] | 3 |
first-completely-painted-row-or-column | Most Optimal Solution ✅Beats 100% | C++| Java | Python | JavaScript | most-optimal-solution-beats-100-c-java-p-w4lv | ⬆️Upvote if it helps ⬆️Connect with me on Linkedin [Bijoy Sing]IntuitionThe key insight is to track the painting progress of each row and column efficiently by | BijoySingh7 | NORMAL | 2025-01-20T04:17:39.090248+00:00 | 2025-01-20T04:17:39.090248+00:00 | 2,237 | false | # ⬆️Upvote if it helps ⬆️
---
## Connect with me on Linkedin [Bijoy Sing]
---
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int row = mat.size();
int col = mat[0].size();
unordered_map<int, pair<int, int>> pos;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
pos[mat[i][j]] = {i, j};
vector<int> rCnt(row, 0);
vector<int> cCnt(col, 0);
for(int i = 0; i < arr.size(); i++) {
auto [r, c] = pos[arr[i]];
rCnt[r]++;
cCnt[c]++;
if(rCnt[r] == col || cCnt[c] == row)
return i;
}
return arr.size() - 1;
}
};
```
```python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
row = len(mat)
col = len(mat[0])
pos = {}
for i in range(row):
for j in range(col):
pos[mat[i][j]] = (i, j)
rCnt = [0] * row
cCnt = [0] * col
for i, val in enumerate(arr):
r, c = pos[val]
rCnt[r] += 1
cCnt[c] += 1
if rCnt[r] == col or cCnt[c] == row:
return i
return len(arr) - 1
```
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int row = mat.length;
int col = mat[0].length;
Map<Integer, int[]> pos = new HashMap<>();
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
pos.put(mat[i][j], new int[]{i, j});
int[] rCnt = new int[row];
int[] cCnt = new int[col];
for(int i = 0; i < arr.length; i++) {
int[] p = pos.get(arr[i]);
rCnt[p[0]]++;
cCnt[p[1]]++;
if(rCnt[p[0]] == col || cCnt[p[1]] == row)
return i;
}
return arr.length - 1;
}
}
```
```javascript []
class Solution {
firstCompleteIndex(arr, mat) {
const row = mat.length;
const col = mat[0].length;
const pos = new Map();
for(let i = 0; i < row; i++)
for(let j = 0; j < col; j++)
pos.set(mat[i][j], [i, j]);
const rCnt = new Array(row).fill(0);
const cCnt = new Array(col).fill(0);
for(let i = 0; i < arr.length; i++) {
const [r, c] = pos.get(arr[i]);
rCnt[r]++;
cCnt[c]++;
if(rCnt[r] === col || cCnt[c] === row)
return i;
}
return arr.length - 1;
}
}
```
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The key insight is to track the painting progress of each row and column efficiently by using a hashmap to store positions and counter arrays.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Create a hashmap to store positions of numbers in matrix
2. Use two arrays to count painted cells in each row and column
3. For each number in arr:
- Get its position from hashmap
- Increment row and column counts
- Check if any row or column is complete
# Complexity
- Time complexity: $$O(m*n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(m*n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
### *If you have any questions or need further clarification, feel free to drop a comment! 😊* | 11 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 5 |
first-completely-painted-row-or-column | ✅ One Line Solution | one-line-solution-by-mikposp-dzps | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code #1.1 - One LineTime complexity: O(m∗n). Space c | MikPosp | NORMAL | 2025-01-20T10:12:10.409134+00:00 | 2025-01-20T21:17:39.308972+00:00 | 759 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)
# Code #1.1 - One Line
Time complexity: $$O(m*n)$$. Space complexity: $$O(m*n)$$.
```python3
class Solution:
def firstCompleteIndex(self, a: List[int], g: List[List[int]]) -> int:
return (d:=dict(zip(a,count()))) and min(map(max,(q:=[[*map(d.get,r)] for r in g])+[*zip(*q)]))
```
# Code #1.2 - Unwrapped
```python3
class Solution:
def firstCompleteIndex(self, a: List[int], g: List[List[int]]) -> int:
d = {v:i for i,v in enumerate(a)}
q = [[d[v] for v in r] for r in g]
return min(map(max, q + [*zip(*q)]))
```
(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better) | 10 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python', 'Python3'] | 0 |
first-completely-painted-row-or-column | C++ || don't use a hash map when a vector or an array does the trick | c-dont-use-a-hash-map-when-a-vector-or-a-fax5 | TODO(heder): Insert cute cat meme to ask for up-votes. ;)\n\n# Approach 1: vector (186ms)\n\nSeveral solutions are using an std::unordered_map for building an i | heder | NORMAL | 2023-04-30T15:20:55.106235+00:00 | 2023-05-02T20:34:04.211431+00:00 | 873 | false | **TODO(heder): Insert cute cat meme to ask for up-votes. ;)**\n\n# Approach 1: vector (186ms)\n\nSeveral solutions are using an ```std::unordered_map``` for building an index, which is a waste as we know that the elements in ```mat``` are within $$[1, n * m]$$, hence we can just directly index into a ```std::vector```.\n\n```cpp\n static int firstCompleteIndex(const vector<int>& arr, const vector<vector<int>>& mat) {\n const int rows = size(mat);\n const int cols = size(mat[0]);\n \n // build index for |mat|.\n vector<pair<int,int>> index(rows * cols + 1);\n for (int r = 0; r < rows; ++r)\n for (int c = 0; c < cols; ++c)\n index[mat[r][c]] = make_pair(r, c);\n \n // process |arr|.\n vector<int> rc(rows);\n vector<int> cc(cols);\n for (int i = 0; i < size(arr); ++i) {\n const auto [r, c] = index[arr[i]];\n if (++rc[r] == cols) return i;\n if (++cc[c] == rows) return i;\n }\n // unreachable.\n assert(false);\n return -1;\n }\n```\n\n**Complexity Analysis**\nLet $$n$$ and $$m$$ be the dimension of ```mat``` and $$n * m$$ the size of ```arr``` then the \n * Time complexity is $$O(n * m)$$ as we need to scan ```mat``` and ```arr``` and the\n * Space complexity is $$O(n * m)$$ for the index we build.\n\n\n# Approach 2: dynamic array on stack (167ms, 100%?)\nAs pointed out @Ajna2, why bother with a vector when an array might be even cheaper. The code is kinda interesting that clang generates for multiple dynamic arrays on the stack: https://godbolt.org/z/h1975ojhj Instead of on the heap the temporary working memory is created on the stack. There is still an indirection happening though.\n\n```cpp\n static int firstCompleteIndex(const vector<int>& arr, const vector<vector<int>>& mat) {\n const int rows = size(mat);\n const int cols = size(mat[0]);\n \n // build index for |mat|.\n pair<int,int> index[rows * cols + 1];\n for (int r = 0; r < rows; ++r)\n for (int c = 0; c < cols; ++c)\n index[mat[r][c]] = make_pair(r, c);\n \n // process |arr|. \n int rc[rows];\n fill(rc, rc + rows, 0);\n int cc[cols];\n fill(cc, cc + cols, 0);\n for (int i = 0; i < size(arr); ++i) {\n const auto [r, c] = index[arr[i]];\n if (++rc[r] == cols) return i;\n if (++cc[c] == rows) return i;\n }\n // unreachable.\n assert(false);\n return -1;\n }\n```\n\nThe complexity analysis remains the same.\n\n**Pro-Tips**\n\nI always have a header like this in my solutions. This speeds-up I/O:\n\n```cpp\n// https://leetcode.com/problems/first-completely-painted-row-or-column\n// problem: 2661\nstatic int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }();\n```\n\n_As always: Feedback, questions, and comments are welcome. Leaving an up-vote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/hFUyVyWy2E)!**\n | 10 | 1 | ['Array', 'C'] | 2 |
first-completely-painted-row-or-column | Testing the soluton | testing-the-soluton-by-datasciencebd2020-wk73 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | datasciencebd2020 | NORMAL | 2025-01-20T22:44:51.321456+00:00 | 2025-01-20T22:44:51.321456+00:00 | 55 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m=mat.length;
int n=mat[0].length;
//Declare array frequency for Row and Column
int[] rowFeq=new int[m];
int[] colFeq=new int[n];
//Set HashMap for the Matrix value corresponding row Index and column Index
Map<Integer, int[]> map=new HashMap<>();
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
map.put(mat[i][j], new int[]{i,j});
}
}
//Traversing the "arr", painting the "mat" cell and increasing the "rowFeq" and "colFeq"
for(int i=0; i<arr.length; i++){
int[] idx=map.get(arr[i]);
int r=idx[0];
int c=idx[1];
rowFeq[r]++;
colFeq[c]++;
//rowFeq[r] will be equal of no. of columns
//colFeq[c] will be equal of no. of rows
if(rowFeq[r]==n || colFeq[c]==m){
return i;
}
}
return -1;
}
}
``` | 9 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | Easy to understand code || Simple Mapping | easy-to-understand-code-simple-mapping-b-u8ke | \nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) \n {\n int m = mat.size(), n = mat[0].size();\n | mohakharjani | NORMAL | 2023-04-30T04:03:34.010958+00:00 | 2023-04-30T04:03:34.010998+00:00 | 2,285 | false | ```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) \n {\n int m = mat.size(), n = mat[0].size();\n vector<int>rowFill(m, 0); //rowFill[i] => how much columns are filled in row = i\n vector<int>colFill(n, 0); //colFill[i] => how much rows are filled in col = i\n //=========================================================================\n vector<int>rowIdxMap((m * n) + 1); //mapping row index and col index for each value\n vector<int>colIdxMap((m * n) + 1);\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n int val = mat[i][j];\n rowIdxMap[val] = i;\n colIdxMap[val] = j;\n }\n }\n //================================================================================\n for (int i = 0; i < arr.size(); i++)\n {\n int val = arr[i];\n int rowIdx = rowIdxMap[val];\n int colIdx = colIdxMap[val];\n \n rowFill[rowIdx]++;\n colFill[colIdx]++;\n if (rowFill[rowIdx] == n || colFill[colIdx] == m) return i;\n }\n //===============================================================================\n return -1;\n \n }\n};\n``` | 8 | 2 | ['Hash Table', 'C', 'C++'] | 2 |
first-completely-painted-row-or-column | C++ | Map | Easy to Understand | c-map-easy-to-understand-by-nidhiigahlaw-051j | Approach\n\nWe first create a map that maps each element in the matrix to its row and column position. Then, for each element in the array, we look up its row a | nidhiii_ | NORMAL | 2023-04-30T04:01:44.794466+00:00 | 2023-04-30T07:12:23.387007+00:00 | 1,288 | false | # Approach\n\nWe first create a map that maps each element in the matrix to its row and column position. Then, for each element in the array, we look up its row and column position in the map and increments the count of elements in that row and column.\n\nIf the count of elements in any row or column reaches the size of the matrix, it means that all the elements needed to complete that row or column have been found. In that case, return the index of the current element in the list.\n\nIf no element completes a row or column, the return -1.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int m=mat.size();\n int n=mat[0].size();\n\n unordered_map<int, int> rowcount, colcount; \n unordered_map<int,pair<int,int>>mp;\n\n for(int i=0;i<m;++i){\n for(int j=0;j<n;++j){\n mp[mat[i][j]]={i,j}; //store the coordinates of each number in the matrix\n }\n }\n\n for(int i=0;i<arr.size();++i){\n int row=mp[arr[i]].first;\n int col=mp[arr[i]].second;\n \n // increment the row and column count for each occurrence\n ++rowcount[row];\n ++colcount[col];\n \n // if any row or column has all the numbers, return the current index \n if(rowcount[row]==n || colcount[col]==m) return i;\n } \n return -1;\n }\n};\n``` | 8 | 0 | ['C++'] | 2 |
first-completely-painted-row-or-column | Just Use A Simple Map | just-use-a-simple-map-by-saswati10-bul9 | \nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n \n int m = mat.length;\n int n = mat[0].length;\n | saswati10 | NORMAL | 2023-04-30T04:13:46.079986+00:00 | 2023-04-30T04:29:52.273627+00:00 | 742 | false | ```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n \n int m = mat.length;\n int n = mat[0].length;\n int r[] = new int[m];\n int c[] = new int[n];\n \n Map<Integer, int[]> map = new HashMap<>();\n \n for(int i = 0; i < m; i++)\n {\n for(int j = 0; j < n; j++)\n {\n map.put(mat[i][j], new int[]{i, j});\n }\n }\n \n for(int i = 0; i < arr.length; i++)\n {\n int[] posi = map.get(arr[i]);\n int x = posi[0];\n int y = posi[1];\n r[x]++;\n c[y]++;\n\t\t\t// any index of r is storing painted columns of that particular row \n\t\t\t// any index of c is storing painted rows of that particular column.\n if(r[x] == n || c[y] == m) // as any column size of a particular row is n and any row size of a particular column is m\n return i;\n }\n return arr.length - 1;\n }\n}\n``` | 7 | 0 | ['Array', 'Java'] | 0 |
first-completely-painted-row-or-column | First Completely Painted Row or Column - Solution Explanation and Code (Video Solution Available) | first-completely-painted-row-or-column-s-u3hw | Video SolutionIntuitionThe problem involves identifying the first index in the array arr that completes a row or a column in the matrix mat. By mapping the matr | CodeCrack7 | NORMAL | 2025-01-20T01:21:41.595932+00:00 | 2025-01-20T01:21:41.595932+00:00 | 553 | false | # Video Solution
[https://youtu.be/vejBP6zxtTY?si=kEPfeh8FK0Enzi_8]()
# Intuition
The problem involves identifying the first index in the array `arr` that completes a row or a column in the matrix `mat`. By mapping the matrix values to their coordinates, we can efficiently track the counts for rows and columns as we iterate through `arr`.
# Approach
1. Create a HashMap to store the coordinates of each value in the matrix `mat`. The key is the matrix value, and the value is an array representing the row and column indices.
2. Maintain two arrays, `row` and `col`, to track the count of marked cells for each row and column, respectively.
3. Iterate through the array `arr`:
- For each value in `arr`, retrieve its coordinates from the HashMap.
- Increment the corresponding row and column counts.
- Check if the current row or column is fully marked. If so, return the current index.
4. If no row or column is fully marked after processing all elements of `arr`, return 1 as the default output.
# Complexity
- **Time complexity**:
- Building the HashMap: $$O(m \cdot n)$$, where $$m$$ is the number of rows and $$n$$ is the number of columns in `mat`.
- Iterating through `arr`: $$O(k)$$, where $$k$$ is the length of `arr`.
- Total: $$O(m \cdot n + k)$$.
- **Space complexity**:
- HashMap storage: $$O(m \cdot n)$$.
- Additional arrays for row and column counts: $$O(m + n)$$.
- Total: $$O(m \cdot n + m + n)$$.
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
// HashMap to store the coordinates of each value in the matrix
HashMap<Integer, int[]> map = new HashMap<>();
// Arrays to track the count of marked cells for each row and column
int[] row = new int[mat.length];
int[] col = new int[mat[0].length];
// Populate the HashMap with matrix value coordinates
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
int[] coordinate = new int[2];
coordinate[0] = i;
coordinate[1] = j;
map.put(mat[i][j], coordinate);
}
}
// Iterate through the array and track row/column completions
for (int i = 0; i < arr.length; i++) {
int[] coordinate = map.get(arr[i]);
int r = coordinate[0];
int c = coordinate[1];
// Increment row and column counts
row[r]++;
col[c]++;
// Check if the current row or column is fully marked
if (row[r] == mat[0].length || col[c] == mat.length) {
return i;
}
}
// Default return value if no row/column is fully marked
return 1;
}
} | 6 | 0 | ['Java'] | 1 |
first-completely-painted-row-or-column | 🔥C++ ✅✅ Best Solution ( 🔥 100% faster 🔥) 0(m*n) Easy to Understand + Comments 💯💯 ⬆⬆⬆ | c-best-solution-100-faster-0mn-easy-to-u-u1pc | Complexity\n- Time complexity: O(m * n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(m * n)\n Add your space complexity here, e.g. O(n) | Sandipan58 | NORMAL | 2023-04-30T04:27:25.228782+00:00 | 2023-04-30T04:27:25.228806+00:00 | 406 | false | # Complexity\n- Time complexity: $$O(m * n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m * n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int n = mat.size(), m = mat[0].size();\n unordered_map<int, pair<int, int> > mp; // this map stores :: value -> {row, column}\n\n // map creation process\n for(int i=0; i<n; i++) {\n for(int j=0; j<m; j++) {\n mp[mat[i][j]] = {i, j};\n }\n }\n \n // initialy all row and column are not visited\n vector<int> row(n, 0); \n vector<int> col(m, 0);\n \n // traversing the array and adding one element to the corresponding row and column\n for(int i=0; i<arr.size(); i++) {\n pair<int, int> p = mp[arr[i]]; // we get the row and column of the cuurent element by the help of our map in O(1) time\n\n int r = p.first, c = p.second;\n\n row[r]++; // adding one element in the corresponding row\n if(row[r] >= m) return i; // here the row is full if row contain m elements\n \n col[c]++; // adding one element in the corresponding row\n if(col[c] >= n) return i; // here the row is full if row contain m elements\n }\n \n return -1;\n }\n};\n``` | 6 | 0 | ['Ordered Map', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | 25 ms || using Hash Map || and two Arrays || Easy to UnderStand | 25-ms-using-hash-map-and-two-arrays-easy-5k26 | Code | sathish-77 | NORMAL | 2025-01-20T08:11:01.620080+00:00 | 2025-01-20T08:12:47.478378+00:00 | 278 | false |
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int[] row=new int[mat[0].length];
int[] col=new int[mat.length];
HashMap<Integer,int[]>map=new HashMap<>();
for(int i=0;i<mat.length;++i){
for(int j=0;j<mat[0].length;++j){
map.put(mat[i][j],new int[]{i,j});
}
}
for(int i=0;i<arr.length;++i){
int[] a=map.get(arr[i]);
row[a[1]]++;
col[a[0]]++;
if(row[a[1]]==mat.length)return i;
if(col[a[0]]==mat[0].length)return i;
}
return -1;
}
}
``` | 5 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 1 |
first-completely-painted-row-or-column | Easy solution 🚀🚀🚀🚀🚀🚀 | easy-solution-by-sharvil_karwa-wm9c | Code | Sharvil_Karwa | NORMAL | 2025-01-20T03:37:33.109615+00:00 | 2025-01-20T03:37:33.109615+00:00 | 571 | false | # Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size(), N = m * n;
vector<int> numToIndex(N + 1, -1);
for (int i = 0; i < N; ++i) {
numToIndex[arr[i]] = i;
}
vector<int> rowPainted(m, 0), colPainted(n, 0);
vector<int> rowPos(N), colPos(N);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int num = mat[i][j];
int indexInArr = numToIndex[num];
rowPos[indexInArr] = i;
colPos[indexInArr] = j;
}
}
for (int i = 0; i < N; ++i) {
int num = arr[i];
int rowIdx = rowPos[numToIndex[num]];
int colIdx = colPos[numToIndex[num]];
if (++rowPainted[rowIdx] == n || ++colPainted[colIdx] == m) {
return i;
}
}
return -1;
}
};
``` | 5 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python', 'C++', 'Java'] | 1 |
first-completely-painted-row-or-column | Optimizing Space | C++, Python (3-lines), Java | reusing-input-array-c-by-not_yl3-mozz | ApproachFirst we create an array/hashmap to map each value from [1,m⋅n] to a pair containing it's row and column index (r, c). Then we create two arrays rows an | not_yl3 | NORMAL | 2025-01-20T02:03:07.859846+00:00 | 2025-01-20T15:19:38.152477+00:00 | 497 | false | # Approach
First we create an array/hashmap to map each value from $$[1, m \cdot n]$$ to a pair containing it's row and column index `(r, c)`. Then we create two arrays `rows` and `cols` of length $$m$$ and $n$ respectively. While itearting through `arr` we get the corresponding indices from our hashmap of pairs and then increment `rows[r]` and `cols[c]` and if `rows[r] == n` or `cols[c] == m` we return the index we're at $$i$$.
Only a slight optimization just for space is reusing the given array instead of creating 2 more arrays `rows` and `cols`. We can use the first row and column in `mat` to store our values intead. Note that since `mat[0][0]` is shared by both, I added an extra value to the end of the first row and 1-indexed the columns. Check the python code at the bottom for reducing the space complexity from $$O(mn + m + n)$$ to $$O(mn)$$.
# Complexity
- Time complexity: $$O(m \cdot n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(m \cdot n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
pair<int, int> map[arr.size() + 1];
for (int r = 0; r < m; r++){
for (int c = 0; c < n; c++){
map[mat[r][c]] = {r, c + 1};
mat[r][c] = 0;
}
}
mat[0].push_back(0);
for (int i = 0; i < arr.size(); i++){
auto& [r, c] = map[arr[i]];
if (++mat[r][0] == n || ++mat[0][c] == m)
return i;
}
return -1;
}
};
```
```python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
map = {mat[r][c]: (r, c) for r in range(m) for c in range(n)}
rows, cols = [0] * m, [0] * n
for i in range(len(arr)):
r, c = map[arr[i]]
rows[r] += 1
cols[c] += 1
if rows[r] == n or cols[c] == m:
return i
return -1
```
```java []
class Solution {
private class Pair{
public int r, c;
Pair(int r, int c) { this.r = r; this.c = c; }
}
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length, n = mat[0].length;
Pair[] map = new Pair[arr.length + 1];
for (int r = 0; r < m; r++){
for (int c = 0; c < n; c++){
map[mat[r][c]] = new Pair(r, c + 1);
mat[r][c] = 0;
}
}
mat[0] = new int[n + 1];
for (int i = 0; i < arr.length; i++){
int r = map[arr[i]].r, c = map[arr[i]].c;
if (++mat[r][0] == n || ++mat[0][c] == m)
return i;
}
return -1;
}
}
```
## Python 3-lines
Here's a version that doesn't use extra space for the `rows` and `cols` arrays and instead gets the max index it would take to paint each row and column one by one by mapping the values in `arr` to their index. To put it simply the minimum index needed to entirely paint any specific row or column is the value that had the highest corresponding index in `arr`.
```python
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
map = {arr[i]: i for i in range(len(arr))}
res = min(max(map[num] for num in row) for row in mat)
return min(res, min(max(map[mat[r][c]] for r in range(len(mat))) for c in range(len(mat[0]))))
```
## C++
```cpp
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
int k = arr.size(), map[k + 1], res = k;
for (int i = 0; i < k; i++)
map[arr[i]] = i;
for (int r = 0; r < m; r++){
int maxIndex = 0;
for (int c = 0; c < n; c++){
if (map[mat[r][c]] > maxIndex)
maxIndex = map[mat[r][c]];
}
if (maxIndex < res) res = maxIndex;
}
for (int c = 0; c < n; c++){
int maxIndex = 0;
for (int r = 0; r < m; r++){
if (map[mat[r][c]] > maxIndex)
maxIndex = map[mat[r][c]];
}
if (maxIndex < res) res = maxIndex;
}
return res;
}
};
``` | 5 | 0 | ['Array', 'Hash Table', 'C', 'Matrix', 'Python', 'C++', 'Java', 'Python3'] | 0 |
first-completely-painted-row-or-column | ✅✅Binary Search Solution || Single Set || No hash map || Unique Approach ☢ | binary-search-solution-single-set-no-has-gy0z | Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nIn this problem I have used Binary search and simple unordered set to solve | 2uringTested | NORMAL | 2023-05-12T08:09:21.604822+00:00 | 2023-05-12T08:09:57.092157+00:00 | 157 | false | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem I have used Binary search and simple unordered set to solve the problem.\n\nThe problem wants us to find the minimum index such that atleast one of the row or column of the matrix is colored. \n\nIn my solution I have represented a colored cell using -1.\n\nInitially I have assumed that the index is at the middle of the array as we do in a binary search.\n\nFor that index = mid, I have put all the elements of array from 0 to mid in a set and called a function "color" which would color a cell if a the value present in the cell is also present in the set. Color would also check if any row or column is fully colored or not, as soon as a row or column is colored, it returns a true value else it returns false.\n\nNow, the main idea is, if at index == mid, atleast one cell is colored then the minimum value of the index for which atleast one cell is colored can only be towards the left of the mid.\n\nSo, now we store mid in our answer and check the left portion of the array like binary search does and update our answer as we go. \n\n\n# Complexity\n- Time complexity: $$O(log(n)*N*M)$$\n- where n is size of array, N is no. of rows of matrix, M is no. of columns in matrix.\n\n# Code\n```\nclass Solution {\npublic:\n using vvi = vector<vector<int>>;\n\n bool color(vvi mat, const unordered_set<int>& nums) {\n bool isColor = true;\n for (int i = 0; i < mat.size(); i++) {\n for (int j = 0; j < mat[0].size(); j++) {\n if (nums.count(mat[i][j])) {\n mat[i][j] = -1;\n } else {\n isColor = false;\n }\n }\n if (isColor) return true;\n isColor = true; // Reset for next row\n }\n \n for (int j = 0; j < mat[0].size(); j++) {\n bool isColor = true;\n for (int i = 0; i < mat.size(); i++) {\n if (mat[i][j] != -1) {\n isColor = false;\n break;\n }\n }\n if (isColor) return true;\n }\n \n return false;\n }\n\n int firstCompleteIndex(const vector<int>& arr, const vvi& mat) {\n int left = 0;\n int right = arr.size() - 1;\n int ans = INT_MAX;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n unordered_set<int> nums(arr.begin(), arr.begin() + mid + 1);\n\n if (color(mat, nums)) {\n ans = min(ans, mid);\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n\n mid = left + (right - left) / 2;\n }\n\n return ans;\n }\n};\n\n``` | 5 | 0 | ['Binary Search', 'Matrix', 'Ordered Set', 'C++'] | 1 |
first-completely-painted-row-or-column | ✅✅✅ Python3 || Easy & Understandable || Explained | python3-easy-understandable-explained-by-9x3u | Intuition\nYou only need to keep track of how many zeroes are there.\n\n# Approach\nFirst, map each item in mat to the row and column indicies so they can be ac | a-fr0stbite | NORMAL | 2023-05-02T05:58:08.866246+00:00 | 2023-05-02T05:58:08.866290+00:00 | 507 | false | # Intuition\nYou only need to keep track of how many zeroes are there.\n\n# Approach\nFirst, map each item in `mat` to the row and column indicies so they can be accessed anywhere. Next, have a list for how many zeroes are in each row and column. Then, loop over `arr` and record the painted cells. Only the 2 recently painted cells can possibly be the last cell painted in a row or column.\n\n\n# Code\n```\nclass Solution:\n def firstCompleteIndex(self, arr, mat):\n rowCols = {}\n ROWS = len(mat)\n COLS = len(mat[0])\n for r in range(ROWS):\n for c in range(COLS):\n rowCols[mat[r][c]] = [r, c] # mapping cells to their r and c\n # variables for keeping track of painted cells in a row or column\n rowZeroes = ROWS * [0]\n colZeroes = COLS * [0]\n for n in range(len(arr)):\n num = arr[n]\n # another 2 painted cells\n rowZeroes[rowCols[num][0]] += 1\n colZeroes[rowCols[num][1]] += 1\n\n\n if colZeroes[rowCols[num][1]] == ROWS: return n\n elif rowZeroes[rowCols[num][0]] == COLS: return n \n```\nWhy did I compare the colZeroes item with ROWS and rowZeroes with COLS?\nNotice that the length of C1 (items are wrapped in ()) is \n how many rows there are and the length of R1(in {}) is how \n many columns there are.\n```\n C1 C2 C3\nR1 [ ({N}) | {N} | {N} ]\nR2 [ (N) | N | N ]\nR3 [ (N) | N | N ]\nR4 [ (N) | N | N ]\n``` | 5 | 0 | ['Python3'] | 0 |
first-completely-painted-row-or-column | Store Row and Col | store-row-and-col-by-votrubac-yvqe | Go through the matrix and, for each number, remember the row and col using mn.\n\nThen, count how many elements are painted in each row and column using mc and | votrubac | NORMAL | 2023-04-30T21:17:13.764659+00:00 | 2023-04-30T21:17:13.764690+00:00 | 274 | false | Go through the matrix and, for each number, remember the row and col using `mn`.\n\nThen, count how many elements are painted in each row and column using `mc` and `nc`.\n\n**C++**\n```cpp\nint firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int m = mat.size(), n = mat[0].size(), k = 0;\n vector<int> mc(m), nc(n);\n vector<array<int, 2>> mn(m * n + 1);\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n mn[mat[i][j]] = {i, j};\n for (; ; ++k)\n if (++mc[mn[arr[k]][0]] == n || ++nc[mn[arr[k]][1]] == m)\n break;\n return k;\n}\n``` | 5 | 0 | ['C'] | 1 |
first-completely-painted-row-or-column | Fully Explained simple Java solution | fully-explained-simple-java-solution-by-eiguu | \n# Approach\nImplement a HashMap and store row and column value for each item.\n\nNow make arrays of row and column of size column and row respectively for get | codeHunter01 | NORMAL | 2023-04-30T04:07:48.026690+00:00 | 2023-04-30T04:07:48.026729+00:00 | 709 | false | \n# Approach\nImplement a HashMap and store row and column value for each item.\n\nNow make arrays of row and column of size column and row respectively for getting the filled size of that row or that column.\n\nFor each value of arr we increase the filled size by one and check if any row or col filled size equals to col or row size respectively and store the minimum index.\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n int size = arr.length;\n int n = mat.length;\n int m = mat[0].length;\n //Implement a HashMap and store row and column value for each item\n HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n map.put(mat[i][j], new ArrayList<Integer>(Arrays.asList(i,j)));\n }\n }\n \n //now make arrays of row and column of size column and row respectively for getting the filled size of that row or that column.\n int[] row = new int[n];\n int[] col = new int[m];\n int rval = Integer.MAX_VALUE;\n int cval =Integer.MAX_VALUE;\n \n // for each value of arr we increase the filled size by one and check if any row or col filled size equals to col or row size respectively and store the minimum index.\n for(int i = 0;i<size;i++)\n {\n int val = arr[i];\n int r=map.get(val).get(0);\n int c=map.get(val).get(1);\n row[r]++;\n if(row[r]==m) rval = Math.min(rval,i);\n col[c]++;\n if(col[c]==n) cval = Math.min(cval,i);\n \n }\n return Math.min(rval,cval);\n }\n}\n``` | 5 | 0 | ['Array', 'Matrix', 'Java'] | 1 |
first-completely-painted-row-or-column | Simple || Clean || Java Solution | simple-clean-java-solution-by-himanshubh-dwmg | \njava []\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n Map<Integer,Integer> map = new HashMap();\n for(int i=0 | HimanshuBhoir | NORMAL | 2023-04-30T04:01:53.432283+00:00 | 2023-04-30T04:01:53.432321+00:00 | 1,118 | false | \n``` java []\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n Map<Integer,Integer> map = new HashMap();\n for(int i=0; i<arr.length; i++) map.put(arr[i],i);\n int min = arr.length;\n// Row-wise checking\n for(int i=0; i<mat.length; i++){\n int max = 0;\n for(int j=0; j<mat[0].length; j++){\n max = Math.max(max, map.get(mat[i][j]));\n }\n min = Math.min(min,max);\n }\n// Col-wise checking\n for(int i=0; i<mat[0].length; i++){\n int max = 0;\n for(int j=0; j<mat.length; j++){\n max = Math.max(max, map.get(mat[j][i]));\n }\n min = Math.min(min,max);\n }\n return min;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | C++ || Map of each row & column | c-map-of-each-row-column-by-up1512001-dbxc | \nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n unordered_map<int,pair<int,int>> mp;\n for | up1512001 | NORMAL | 2023-04-30T04:01:16.190028+00:00 | 2023-04-30T04:01:16.190074+00:00 | 653 | false | ```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n unordered_map<int,pair<int,int>> mp;\n for(int i=0;i<mat.size();i++){\n for(int j=0;j<mat[0].size();j++){\n mp[mat[i][j]] = {i,j};\n }\n }\n map<int,int> r,c;\n for(int i=0;i<arr.size();i++){\n auto x = mp[arr[i]];\n r[x.first] += 1;\n c[x.second] += 1;\n \n if(r[x.first] == mat[0].size() || c[x.second] == mat.size()) return i;\n }\n return -1;\n }\n};\n``` | 5 | 0 | ['C', 'C++'] | 1 |
first-completely-painted-row-or-column | Simple py,JAVA code exaplined in detail!! HASH+ARRAY | simple-pyjava-code-exaplined-in-detail-h-2xt7 | Problem understanding
They have given us a mtrix mat which has row rows and col columns.
They have also given us a array arr which tells us the grids which we s | arjunprabhakar1910 | NORMAL | 2025-01-20T11:49:01.201771+00:00 | 2025-01-20T11:49:01.201771+00:00 | 99 | false | # Problem understanding
- They have given us a mtrix `mat` which has `row` rows and `col` columns.
- They have also given us a array `arr` which tells us the grids which we should mark as painted in the matrix.
- we will traverse through the array from `0,1......arr.length`.when either of the *row* or *col* is completely ***painted*** we return `i`.
---
# Approach:3Hash/Hash+2Array
<!-- Describe your approach to solving the problem. -->
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- To acess the matrix position `(i,j)` while traversing array `arr` we will use a hash named `hash` which will store *mat[i][j]* as a key and *(i,j)* as value thus help in constant $O(1)$ acess.
- Then we will use `rowHash` and `colHash` to count the frequency of no of rows and columns filled.This can be a dictionary or array.
- when any `rowHash` equals to `col` and any `colHash` equals `row` we return `i`.
# Complexity
- Time complexity:$O(n^2)$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$O(n^2)$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```Python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
row,col=len(mat),len(mat[0])
hash=dict()
#populating hash
for i in range(row):
for j in range(col):
hash[mat[i][j]]=(i,j)
rowHash={i:0 for i in range(row)}
colHash={i:0 for i in range(col)}
for i in range(len(arr)):
x,y=hash[arr[i]]
rowHash[x]+=1
colHash[y]+=1
if rowHash[x]==col or colHash[y]==row:
return i
return -1
```
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int row=mat.length;
int col=mat[0].length;
Map<Integer,int[]> hash=new HashMap<>();
//populating hahs to access O(1)!
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
hash.put(mat[i][j],new int[]{i,j});
}
}
//we can use array instead of dictionary to calculate freq!!
int[] rowHash=new int[row];
int[] colHash=new int[col];
//key-logic
for(int i=0;i<arr.length;i++){
int[] pop=hash.get(arr[i]);
int x=pop[0];
int y=pop[1];
rowHash[x]++;
colHash[y]++;
if(rowHash[x]==col || colHash[y]==row){
return i;
}
}
return -1;
}
}
``` | 4 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java', 'Python3'] | 0 |
first-completely-painted-row-or-column | Super Simple Solution in java/C Using Freq(track index) ( O(n*m) ) | super-simple-solution-in-javac-using-fre-a5w7 | IntuitionSince we need to check for a completed row/column we can use freq/index arr to track the last used index for each individual row/col using the freq/ind | rajnarayansharma110 | NORMAL | 2025-01-20T06:26:09.297441+00:00 | 2025-01-20T06:27:17.036131+00:00 | 179 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Since we need to check for a completed row/column we can use freq/index arr to track the last used index for each individual row/col using the freq/index arr
# Approach
<!-- Describe your approach to solving the problem. -->
1. Store the idx of each elem of arr in freq array( this will help us to find the minimum idx at which we can have a completed row or column )
2. Now we check each row by row to find the minimum index of arr at which the row is completed.
3. Similar to above we check each column by column to find the minimum index of arr at which the column is completed.
4. return the smallest idx.
# Complexity
- Time complexity:O(n*m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O( Max(arr) )
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int res = Integer.MAX_VALUE, m = mat.length, n = mat[0].length, max = 0;
for (int a : arr)
max = Math.max(a, max);
int[] freq = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
freq[arr[i]] = i;
}
for (int i = 0; i < m; i++) {
int lastNumIdx = Integer.MIN_VALUE;
for (int j = 0; j < n; j++) {
int idx = freq[mat[i][j]];
lastNumIdx = Math.max(lastNumIdx, idx);
}
res = Math.min(res, lastNumIdx);
}
for (int j = 0; j < n; j++) {
int lastNumIdx = Integer.MIN_VALUE;
for (int i = 0; i < m; i++) {
int idx = freq[mat[i][j]];
lastNumIdx = Math.max(lastNumIdx, idx);
}
res = Math.min(res, lastNumIdx);
}
return res;
}
}
```
```C []
int firstCompleteIndex(int* arr, int arrSize, int** mat, int matSize,int* matColSize) {
int m = matSize, n = matColSize[0], max = 0, res = INT_MAX;
for (int i = 0; i < arrSize; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int* freq = (int*)calloc(max + 1, sizeof(int));
for (int i = 0; i < arrSize; i++) {
freq[arr[i]] = i;
}
for (int i = 0; i < m; i++) {
int lastNumIdx = INT_MIN;
for (int j = 0; j < n; j++) {
int idx = freq[mat[i][j]];
if (idx > lastNumIdx) {
lastNumIdx = idx;
}
}
if (lastNumIdx < res) {
res = lastNumIdx;
}
}
for (int j = 0; j < n; j++) {
int lastNumIdx = INT_MIN;
for (int i = 0; i < m; i++) {
int idx = freq[mat[i][j]];
if (idx > lastNumIdx) {
lastNumIdx = idx;
}
}
if (lastNumIdx < res) {
res = lastNumIdx;
}
}
return res;
}
``` | 4 | 0 | ['Hash Table', 'C', 'Java'] | 0 |
first-completely-painted-row-or-column | 🎯Easy || C++ || Python || Java ||✨Hash Table ||👌Beginner-Friendly | easy-c-python-java-hash-table-beginner-f-9rk7 | IntuitionThe idea behind this solution is to determine the first index in the array arr that completes either a row or a column in the matrix mat. Completion of | Rohithaaishu16 | NORMAL | 2025-01-20T06:24:06.869034+00:00 | 2025-01-20T06:24:06.869034+00:00 | 135 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The idea behind this solution is to determine the first index in the array arr that completes either a row or a column in the matrix mat. Completion of a row or column means that all elements in that row or column have been seen in the sequence up to that index.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Mapping Matrix Elements to Their Positions: Use an unordered map (`mp`) to store the positions (row and column indices) of each element in the matrix `mat`.
2. Count Down Rows and Columns: Maintain two vectors, `r` and `c`, to track the remaining unvisited elements in each row and column, respectively.
3. Iterate Through arr: For each element in the array `arr`, decrement the corresponding `row` and `column` counts. If any row or column count reaches zero, that means the row or column is fully covered, and we return the current index.
# Complexity
- Time complexity: $$O(m \times n)$$ to populate the map and $$O(k)$$ to iterate through the array arr, where m is the number of rows, n is the number of columns, and k is the size of arr. Overall, the time complexity is $$O(m \times n + k)$$.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(m \times n)$$ for storing positions in the map, and $$O(m + n)$$ for the row and column count vectors. Overall, the space complexity is $$O(m \times n)$$.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
unordered_map<int,pair<int,int>> mp;
vector<int> r(m,n), c(n,m);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
mp[mat[i][j]] = {i,j};
for(int i=0;i<arr.size();i++){
auto [row, col] = mp[arr[i]];
if(--r[row]==0 || --c[col]==0) return i;
}
return -1;
}
};
```
```python []
from typing import List, Tuple
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
mp = {}
r = [n] * m
c = [m] * n
for i in range(m):
for j in range(n):
mp[mat[i][j]] = (i, j)
for i in range(len(arr)):
row, col = mp[arr[i]]
if r[row] - 1 == 0 or c[col] - 1 == 0:
return i
r[row] -= 1
c[col] -= 1
return -1
```
```java []
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length, n = mat[0].length;
Map<Integer, int[]> mp = new HashMap<>();
int[] r = new int[m];
int[] c = new int[n];
for(int i = 0; i < m; i++) {
r[i] = n;
}
for(int i = 0; i < n; i++) {
c[i] = m;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
mp.put(mat[i][j], new int[]{i, j});
}
}
for(int i = 0; i < arr.length; i++) {
int[] pos = mp.get(arr[i]);
int row = pos[0], col = pos[1];
r[row]--;
c[col]--;
if(r[row] == 0 || c[col] == 0) return i;
}
return -1;
}
}
``` | 4 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++', 'Java', 'Python3'] | 0 |
first-completely-painted-row-or-column | Easy-to-understand✅✅ || Simple Hash Table Apprach 🚀🚀 || C++ 🔥🔥|| Java 🗿🗿 || Python3 💀💀 | easy-to-understand-simple-hash-table-app-a3se | IntuitionThe problem asks us to find the smallest index i such that when we paint the cell corresponding to arr[i] in the matrix mat, a row or a column becomes | Sparsh_786 | NORMAL | 2025-01-20T06:09:32.031733+00:00 | 2025-01-20T06:09:32.031733+00:00 | 304 | false | # Intuition
The problem asks us to find the smallest index $$i$$ such that when we paint the cell corresponding to $$arr[i]$$ in the matrix mat, a row or a column becomes completely painted. The matrix mat has all integers in the range $$[1, m*n]$$, and the array arr gives us the order in which these integers are painted.
The solution leverages efficient tracking of painted rows and columns while iterating through the numbers in arr. By marking rows and columns whenever a number is painted, we can easily detect when either a row or column becomes completely painted.
# Approach
- Store the position $$(i, j) $$of each number in the matrix mat using an array pos.
- Use a map $$m1$$ to count how many cells in each row and column are painted.
Keys: $${'R', i}$$ for rows and $${'C', j}$$ for columns.
- For each number in arr, find its position in mat using pos.
Increment the count for the corresponding row and column in m1.
- After each paint, check if the count of painted cells in the row equals the number of columns or in the column equals the number of rows.
- If a row or column is fully painted, return the current index.
If no row or column is fully painted, return $$-1$$.
# Complexity
- Time complexity: $$O(m*n + n*log(m*n))$$
- Space complexity: $$O(m*n)$$
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n = arr.size();
int row = mat.size(), col = mat[0].size();
int index = 0;
map<pair<char,int>, int> m1;
vector<pair<int,int>> pos(row*col+1);
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
pos[mat[i][j]] = {i, j};
}
}
while(index<n) {
auto curr = pos[arr[index]];
int i = curr.first;
int j = curr.second;
m1[{'R',i}]++;
m1[{'C',j}]++;
if(m1[{'R',i}]==col || m1[{'C',j}]==row)
return index;
index++;
}
return -1;
}
};
```
```java []
import java.util.*;
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n = arr.length;
int row = mat.length, col = mat[0].length;
int index = 0;
Map<String, Integer> m1 = new HashMap<>();
int[][] pos = new int[row * col + 1][2];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
pos[mat[i][j]] = new int[]{i, j};
}
}
while (index < n) {
int[] curr = pos[arr[index]];
int i = curr[0];
int j = curr[1];
m1.put("R" + i, m1.getOrDefault("R" + i, 0) + 1);
m1.put("C" + j, m1.getOrDefault("C" + j, 0) + 1);
if (m1.get("R" + i) == col || m1.get("C" + j) == row) {
return index;
}
index++;
}
return -1;
}
}
```
```python []
class Solution:
def firstCompleteIndex(self, arr, mat):
n = len(arr)
row, col = len(mat), len(mat[0])
index = 0
m1 = {}
pos = [[0, 0] for _ in range(row * col + 1)]
for i in range(row):
for j in range(col):
pos[mat[i][j]] = [i, j]
while index < n:
i, j = pos[arr[index]]
m1['R' + str(i)] = m1.get('R' + str(i), 0) + 1
m1['C' + str(j)] = m1.get('C' + str(j), 0) + 1
if m1['R' + str(i)] == col or m1['C' + str(j)] == row:
return index
index += 1
return -1
```

| 4 | 0 | ['Array', 'Hash Table', 'Matrix', 'Hash Function', 'Python', 'C++', 'Java', 'Python3'] | 0 |
first-completely-painted-row-or-column | First Completely Painted Row in RUBY! | first-completely-painted-row-in-ruby-by-8bg5r | IntuitionWhen I first saw this problem, I realized we need to efficiently track two things:
Where each number is located in the matrix
How many cells are painte | quantummaniac609 | NORMAL | 2025-01-20T05:00:26.203492+00:00 | 2025-01-20T05:00:26.203492+00:00 | 51 | false | # Intuition
When I first saw this problem, I realized we need to efficiently track two things:
1. Where each number is located in the matrix
2. How many cells are painted in each row and column
The key insight was that instead of searching the matrix each time, we could pre-compute the positions of all numbers.
# Approach
1. **Position Mapping**:
- Create a hash map that stores the position (row, col) of each number in the matrix
- This allows O(1) lookup of where each number is located
2. **Track Painted Cells**:
- Use two arrays to count painted cells:
- `row_count`: tracks painted cells in each row
- `col_count`: tracks painted cells in each column
3. **Process Array**:
- For each number in the input array:
- Find its position using the hash map
- Increment counters for its row and column
- Check if either counter reaches the required value (n for rows, m for columns)
# Complexity
- Time complexity: $$O(m * n)$$
- One-time cost to build position map
- Processing array is O(m*n) in worst case
- Each lookup and counter update is O(1)
- Space complexity: $$O(m * n)$$
- Position map stores m*n entries
- Counter arrays use O(m + n) space
# Code
```ruby
def first_complete_index(arr, mat)
m, n = mat.length, mat[0].length
# Create hash map to store positions of numbers in matrix
pos = {}
(0...m).each do |i|
(0...n).each do |j|
pos[mat[i][j]] = [i, j]
end
end
# Arrays to track painted cells in each row and column
row_count = Array.new(m, 0)
col_count = Array.new(n, 0)
# Process array elements
arr.each_with_index do |num, idx|
row, col = pos[num]
row_count[row] += 1
col_count[col] += 1
# Check if any row or column is complete
return idx if row_count[row] == n || col_count[col] == m
end
-1 # Should never reach here given constraints
end
``` | 4 | 0 | ['Ruby'] | 0 |
first-completely-painted-row-or-column | Simple Logic ... Easy Approach ... Happy Coding🌞 | simple-logic-easy-approach-happy-coding-t4od4 | Intuitionstore the indexes of elements of matrix in an unordered_mapApproach1.Iterate through the array and push the row and column from the map into the row an | sourav12345singhpraval | NORMAL | 2025-01-20T02:30:45.222844+00:00 | 2025-01-20T02:30:45.222844+00:00 | 391 | false | # Intuition
store the indexes of elements of matrix in an unordered_map
# Approach
1.Iterate through the array and push the row and column from the map into the row and column vector.
2.check that if the size of the vector becomes equal to total number of rows or columns . return the i at that point
# Complexity
- Time complexity:
O(N*M)
- Space complexity:
O(N*M)
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n=mat.size();
int m=mat[0].size();
unordered_map<int,pair<int,int>> mp;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
mp[mat[i][j]]={i,j};
}
}
vector<vector<int>> row(n);
vector<vector<int>> col(m);
for(int i=0;i<arr.size();i++){
pair<int,int> p=mp[arr[i]];
row[p.first].push_back(1);
col[p.second].push_back(1);
if(row[p.first].size()==m){
return i;
}
if(col[p.second].size()==n){
return i;
}
}
return 1;
}
};
``` | 4 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | C++ || MATH || EASY TO UNDERSTAND | c-math-easy-to-understand-by-ganeshkumaw-3awo | Intuition\nstore index{i,j} of every element of matrix \n\n# Approach\nfor an element at index x of arr get{i,j} increment r[i] and c[j] by 1\nif r[i] came n ti | ganeshkumawat8740 | NORMAL | 2023-05-06T07:05:41.494387+00:00 | 2023-05-06T07:05:41.494414+00:00 | 663 | false | # Intuition\nstore index{i,j} of every element of matrix \n\n# Approach\nfor an element at index x of arr get{i,j} increment r[i] and c[j] by 1\nif r[i] came n time than return index x\nif c[j] came m time than return index x\n# Complexity\n- Time complexity:\nO(m*n)\n\n- Space complexity:\nO(m*n)\n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int i,j,m=mat.size(),n=mat[0].size();\n vector<vector<int>> v(m*n);\n vector<int> r(m,0),c(n,0);\n for(i = 0; i < m; i++){\n for(j = 0; j < n; j++){\n v[mat[i][j]-1] = {i,j};\n }\n }\n for(i = 0; i < m*n; i++){\n r[v[arr[i]-1][0]]++;\n c[v[arr[i]-1][1]]++;\n // cout<<arr[i]<<" "<<v[arr[i]-1][0]<<" "<<v[arr[i]-1][1]<<" "<<r[v[arr[i]-1][0]]<<" "<<c[v[arr[i]-1][1]]<<endl;\n if(r[v[arr[i]-1][0]] == n)return i;\n if(c[v[arr[i]-1][1]] == m)return i;\n }\n return -1;\n }\n};\n``` | 4 | 0 | ['Math', 'C++'] | 0 |
first-completely-painted-row-or-column | ✅🚀 || HashMap || Well explained || JAVA || Clean code | hashmap-well-explained-java-clean-code-b-cja0 | Intuition\n Describe your first thoughts on how to solve this problem. \nHere, all we need to find is the index of the element from arr[i] in the matrix.\nFor e | aeroabrar_31 | NORMAL | 2023-04-30T04:09:02.794508+00:00 | 2023-04-30T04:09:02.794541+00:00 | 539 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere, all we need to find is the index of the element from arr[i] in the matrix.\nFor every element we need to find the index and to keep the count of number of elements in each row and each column, so the time complexity will be $$O(len*(m*n))$$ where len is length of array.\nNow, let\'s talk about the constraints.\narr.length == m * n\n1 <= m, n <= 10^5\n1 <= m * n <= 10^5\n\nClearly, in the worst case there will be TLE error.\n\nSo, all we need a data structure which can be used to search the index of the arr[i] in a constant time.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHashMap is the only data structure which can help us to find the index of arr[i] in a constant time.\nWe will be keep tracking the number of elements in each row and each column by using temporary arrays.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(m*n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(m*n)$$\n\n# Code\n```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n \n int m=mat.length;\n int n=mat[0].length;\n \n int[] rows=new int[m];\n int[] cols=new int[n];\n \n \n HashMap<Integer,Pair> map=new HashMap<>();\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n map.put(mat[i][j],new Pair(i,j));\n }\n }\n \n \n for(int i=0;i<arr.length;i++)\n {\n Pair p=map.get(arr[i]);\n \n int r=p.i;\n int c=p.j;\n \n rows[r]++;\n cols[c]++; \n \n if(rows[r]==n || cols[c]==m)\n return i;\n }\n \n return -1;\n \n }\n}\n\nclass Pair\n{\n int i,j;\n \n Pair(int i,int j)\n {\n this.i=i;\n this.j=j;\n }\n}\n``` | 4 | 0 | ['Hash Table', 'Java'] | 0 |
first-completely-painted-row-or-column | Unique C++ easy solution without using Pairs | unique-c-easy-solution-without-using-pai-5xe9 | ApproachA map (positionMap) stores each element's position in mat for quick lookup.Two arrays, rowCount and colCount, track how many elements have been marked i | vasanthkokkiligadda | NORMAL | 2025-01-20T17:12:43.652514+00:00 | 2025-01-20T17:16:22.231468+00:00 | 49 | false | # Approach
A map (positionMap) stores each element's position in mat for quick lookup.
Two arrays, rowCount and colCount, track how many elements have been marked in each row and column.
For each element in arr, its position is determined, and the respective row and column counts are updated.
As soon as a row or column is fully marked, the current index is returned. If no row or column is completed, return -1.
# Complexity
- Time complexity: O(rows * columns)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(rows * columns)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int rows = mat.size(), cols = mat[0].size();
// Map to store the position of each element in the matrix
// Key: Matrix value, Value: Linear index (row * cols + col)
unordered_map<int, int> positionMap;
// Vectors to keep track of the count of marked elements in each row and column
vector<int> rowCount(rows, 0), colCount(cols, 0);
// Populate the positionMap with the position of each element in the matrix
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
positionMap[mat[r][c]] = r * cols + c; // Store linear index
}
}
// Iterate through the elements in the `arr` vector to simulate marking the elements
for (int i = 0; i < arr.size(); i++) {
int val = arr[i]; // Current value to mark
// Retrieve the row and column of the current value using the positionMap
int row = positionMap[val] / cols; // Extract row index from linear index
int col = positionMap[val] % cols; // Extract column index from linear index
// Increment the count of marked elements for the corresponding row and column
if (++rowCount[row] == cols || ++colCount[col] == rows) {
// If the current row or column is completely marked, return the current index
return i;
}
}
// If no row or column gets completely marked, return -1
return -1;
}
``` | 3 | 0 | ['C++'] | 1 |
first-completely-painted-row-or-column | 💢Faster✅💯 Lesser C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 💯 | faster-lesser-cpython3javacpythoncexplai-oule | IntuitionApproach
JavaScript Code --> https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514806461
C++ Code --> https://leetcode. | Edwards310 | NORMAL | 2025-01-20T17:04:36.410789+00:00 | 2025-01-20T17:12:58.751974+00:00 | 63 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your first thoughts on how to solve this problem. -->
- ***JavaScript Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514806461
- ***C++ Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514693402
- ***Python3 Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514765443
- ***Java Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514750490
- ***C Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514808907
- ***Python Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514764219
- ***C# Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514808193
- ***Go Code -->*** https://leetcode.com/problems/first-completely-painted-row-or-column/submissions/1514805774
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(N * M)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(N * M)
# Code
 | 3 | 0 | ['Array', 'Hash Table', 'C', 'Matrix', 'Python', 'C++', 'Java', 'Go', 'Python3', 'C#'] | 0 |
first-completely-painted-row-or-column | ✅🔥Beating 99.5% | 🔥BRUTEFORCE → OPTIMAL🔥| Detailed Expiation✅ | beating-995-bruteforce-optimal-detailed-h98i5 | Intuition
The goal is to find the first index in the array arr such that a row or column in the matrix mat is completely marked (or filled).
The problem revo | syedtahaseen123 | NORMAL | 2025-01-20T15:04:04.853594+00:00 | 2025-01-20T15:04:04.853594+00:00 | 48 | false | # Intuition
- The goal is to find the first index in the array arr such that a row or column in the matrix mat is completely marked (or filled).
- The problem revolves around efficiently marking matrix cells and checking the row/column completion condition.
# BRUTEFORCE$$ [TLE]$$
1. Iterate over the elements of arr.
2. Find the position of the current element in mat using a nested loop.
3. Mark the corresponding position in mat as visited (e.g., -1).
4. After marking, check if the row or column of the marked cell is fully visited.
5. If yes, return the index in arr.
# Complexity
- Time complexity: $$ O(N×M×N×M)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean checkRowCol(int[][] mat, int r, int c)
{
int r1 = 0, c1=0;
for(;r1<mat.length; r1++)
if(mat[r1][c]!=-1)
break;
if(r1==mat.length) return true;
for(;c1<mat[0].length; c1++)
if(mat[r][c1]!=-1)
break;
return c1==mat[0].length;
}
public int[] markIndex(int ele,int[][] mat)
{
for(int i=0; i<mat.length; i++)
{
for(int j=0; j<mat[i].length; j++)
{
if(mat[i][j]==ele)
return new int[]{i,j};
}
}
return new int[]{0,0};
}
public int firstCompleteIndex(int[] arr, int[][] mat) {
for(int i=0; i<arr.length; i++)
{
int[] ind = markIndex(arr[i],mat);
mat[ind[0]][ind[1]] = -1;
if(checkRowCol(mat,ind[0],ind[1])) return i;
}
return 0;
}
}
```
# OPTIMAL
1. Preprocess the mat to create mappings (row and col) from matrix values to their row/column indices.
2. Use arrays rowCount and colCount to track the count of marked cells in each row and column.
3. For each element in arr, directly locate its row and column using the preprocessed mappings.
4. Update the counters for the respective row and column, and return the index if a row or column is fully marked.
# Complexity
- Time complexity: $$ O(N×M)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(N×M)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n = mat.length, m = mat[0].length;
int[] rowCount = new int[n];
int[] colCount = new int[m];
int[] row= new int[m*n+1];
int[] col = new int[m*n+1];
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
row[mat[i][j]] = i;
col[mat[i][j]] = j;
}
}
for(int i=0; i<m*n; i++)
{
int ele = arr[i];
int r = row[ele];
int c = col[ele];
rowCount[r]++;
colCount[c]++;
if(rowCount[r]==m || colCount[c]==n) return i;
}
return 0;
}
}
```
| 3 | 0 | ['Hash Table', 'Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | ✅✅Beats 100%🔥C++🔥Python|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥C++✅✅ | beats-100cpython-super-simple-and-effici-5y73 | Complexity
Time complexity: O(mn)
Space complexity: O(mn)
Code | shobhit_yadav | NORMAL | 2025-01-20T12:43:19.207724+00:00 | 2025-01-20T12:43:19.207724+00:00 | 53 | false | # Complexity
- Time complexity: $$O(mn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(mn)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
const int m = mat.size();
const int n = mat[0].size();
vector<int> rows(m);
vector<int> cols(n);
vector<int> numToRow(m * n + 1);
vector<int> numToCol(m * n + 1);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
numToRow[mat[i][j]] = i;
numToCol[mat[i][j]] = j;
}
for (int i = 0; i < arr.size(); ++i) {
if (++rows[numToRow[arr[i]]] == n)
return i;
if (++cols[numToCol[arr[i]]] == m)
return i;
}
throw;
}
};
```
```python3 []
class Solution:
def firstCompleteIndex(self, arr: list[int], mat: list[list[int]]) -> int:
m = len(mat)
n = len(mat[0])
rows = [0] * m
cols = [0] * n
numToRow = [0] * (m * n + 1)
numToCol = [0] * (m * n + 1)
for i, row in enumerate(mat):
for j, num in enumerate(row):
numToRow[num] = i
numToCol[num] = j
for i, a in enumerate(arr):
rows[numToRow[a]] += 1
if rows[numToRow[a]] == n:
return i
cols[numToCol[a]] += 1
if cols[numToCol[a]] == m:
return i
``` | 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python3'] | 0 |
first-completely-painted-row-or-column | Simple Approach || Step by Step Explanation || Beats 100% | simple-approach-step-by-step-explanation-0ct8 | Intuition
Since the 2-d array mat contains elements from 1 to m*n, we can try thinking of a approach where we can take advantage of this constraint.
Also try th | shivamp_07 | NORMAL | 2025-01-20T11:05:07.946385+00:00 | 2025-01-20T11:05:07.946385+00:00 | 63 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
1. Since the 2-d array mat contains elements from 1 to m*n, we can try thinking of a approach where we can take advantage of this constraint.
2. Also try thinking about thinking row wise and column wise separately, this can help in building the approach on how to simulate the updates and check whether an entire row or column has been filled.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Since elements are constrained between 1 to n*m, store the row and column values for each element of mat array in a 2-d array rowcol, which can be further used while we traverse in array arr.
2. Maintain two arrays for rows and columns, namely row(n, 0) and col(m, 0) check initially initialised to zero as no element has been processed yet.
3. Now start traversing in the array arr, let x = arr[i], find the row value and column value from rowcol[x], and increase count of row[row_value] and col[col_value] by 1.
4. If row[row_value] becomes m, this means all elements of this row has been filled.
Similarly, if col[col_value] becomes n, this means all elements of this column has been filled.
5. Return the index whenever you find any of the conditions in step 4 to be true.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n*m) + O(ans), since we will traverse in array arr till ans index only.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n*m) for rowcol 2-d array.
O(n) + O(m) for row and col arrays for maintaining counts processed.
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<pair<int, int>> rowcol(n*m + 1);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
rowcol[mat[i][j]] = {i, j};
}
}
vector<int> row(n, 0), col(m, 0);
for(int i=0; i<arr.size(); i++){
int r = rowcol[arr[i]].first;
int c = rowcol[arr[i]].second;
row[r]++;
col[c]++;
if(row[r] == m || col[c] == n) return i;
}
return 0;
}
};
``` | 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Simple solution with explanation beat 83.33% in time and space | simple-solution-with-explanation-beat-83-znvc | IntuitionThe key to solving this problem is building an index mapping, which maps each number to its corresponding row and column. This allows us to efficiently | whats2000 | NORMAL | 2025-01-20T10:34:07.146352+00:00 | 2025-01-20T10:34:07.146352+00:00 | 76 | false | # Intuition
The key to solving this problem is building an index mapping, which maps each number to its corresponding row and column. This allows us to efficiently locate the rows and columns, and keep track of their painted counts. When the count equals $m$ (for a row) or $n$ (for a column), we can determine the result.
To build the mapping efficiently, we can use two arrays: one for the rows and one for the columns. This ensures that we can quickly retrieve the corresponding row or column for a number. While a dictionary is also an option, array lookups are generally faster than dictionary operations.
# Approach
## Step 1: Obtain the matrix dimensions
```typescript
const n = mat.length; // Number of rows
const m = mat[0].length; // Number of columns
```
## Step 2: Create the row and column mapping
```typescript
// Arrays to map each number to its row and column
const numberToRow: number[] = new Array(n * m);
const numberToCol: number[] = new Array(n * m);
// Traverse the matrix to build the mapping
for (let row = 0; row < n; row++) {
for (let col = 0; col < m; col++) {
const value = mat[row][col];
numberToRow[value] = row;
numberToCol[value] = col;
}
}
```
## Step 3: Use the mappings to track counts and find the result
```typescript
// Arrays to track the painted counts for rows and columns
const rowCounts: number[] = new Array(n).fill(0);
const colCounts: number[] = new Array(m).fill(0);
// Traverse `arr` and update the counts
for (let i = 0; i < arr.length; i++) {
const current = arr[i];
const row = numberToRow[current];
const col = numberToCol[current];
// Increment the counts for the corresponding row and column
rowCounts[row]++;
colCounts[col]++;
// Check if a row or column is completely painted
if (rowCounts[row] === m || colCounts[col] === n) {
return i; // Return the index when found
}
}
```
## Step 4: Return `-1` if no result is found
```typescript
// Return -1 if no row or column is completely painted
return -1;
```
While the problem guarantees that an answer exists, returning `-1` is a good practice for robustness in real-world scenarios.
# Complexity
- Time complexity:
- Building the index mapping: $O(n \times m)$
- Traversing `arr`: $O(n \times m)$
- Total: $O(n \times m)$
- Space complexity:
- Two mapping arrays: $O(n \times m)$
- Two counting arrays: $O(n + m)$
- Total: $O(n \times m)$
# Code
```typescript
function firstCompleteIndex(arr: number[], mat: number[][]): number {
const n = mat.length; // Number of rows
const m = mat[0].length; // Number of columns
// Arrays to map each number in the matrix to its row and column indices
const numberToRow: number[] = new Array(n * m);
const numberToCol: number[] = new Array(n * m);
// Preprocess the matrix to create a direct mapping of numbers to their row and column
for (let row = 0; row < n; row++) {
for (let col = 0; col < m; col++) {
const value = mat[row][col];
numberToRow[value] = row;
numberToCol[value] = col;
}
}
// Arrays to track how many elements have been filled in each row and column
const rowCounts: number[] = new Array(n).fill(0);
const colCounts: number[] = new Array(m).fill(0);
// Process the `arr` to find the first completed row or column
for (let i = 0; i < arr.length; i++) {
const current = arr[i];
const row = numberToRow[current];
const col = numberToCol[current];
// Update row and column counts
rowCounts[row]++;
colCounts[col]++;
// Check if the current row or column is completed, we will return the index if it is
if (rowCounts[row] === m || colCounts[col] === n) {
return i;
}
}
// Return -1 if no row or column is completed
return -1;
}
```
# Result

| 3 | 0 | ['Array', 'TypeScript'] | 0 |
first-completely-painted-row-or-column | ✅ Easy to Understand | Hash Table | Java | C++ | Python | Detailed Video Explanation 🔥 | easy-to-understand-hash-table-java-c-pyt-30r8 | IntuitionThe problem involves determining the first point in an array where marking an element leads to a complete row or column being filled in a matrix. My in | sahilpcs | NORMAL | 2025-01-20T09:28:44.100083+00:00 | 2025-01-20T09:28:44.100083+00:00 | 82 | false | # Intuition
The problem involves determining the first point in an array where marking an element leads to a complete row or column being filled in a matrix. My initial thought was to map each element of the matrix to its respective coordinates, allowing quick access to the element's position. By maintaining counts of marked elements in each row and column, we can efficiently detect when a row or column is fully marked.
# Approach
1. **Mapping Matrix Elements**:
- Use a `HashMap` to store each element in the matrix as a key and its coordinates (row, column) as the value.
- This allows for O(1) lookup of an element's position.
2. **Counting Marked Elements**:
- Maintain two arrays, `rowc` and `colc`, to keep track of how many elements are marked in each row and column, respectively.
3. **Marking Process**:
- Iterate through the input array `arr`, and for each element:
- Retrieve its coordinates from the map.
- Increment the count in the respective row and column.
- Check if the current row or column is completely marked.
- If a row or column becomes fully marked, return the current index in `arr`.
4. **Termination**:
- If no row or column is fully marked after processing all elements, return `-1`.
# Complexity
- **Time complexity**:
- Creating the map: $$O(m \times n)$$, where $$m$$ is the number of rows and $$n$$ is the number of columns in the matrix.
- Processing the array `arr`: $$O(k)$$, where $$k$$ is the length of the array.
- Overall: $$O(m \times n + k)$$.
- **Space complexity**:
- The `HashMap` requires $$O(m \times n)$$ space to store the matrix elements.
- The `rowc` and `colc` arrays require $$O(m + n)$$ space.
- Overall: $$O(m \times n + m + n)$$.
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
// Map to store the matrix elements as keys and their coordinates (row, column) as values
Map<Integer, int[]> map = new HashMap<>();
int m = mat.length; // Number of rows in the matrix
int n = mat[0].length; // Number of columns in the matrix
// Populate the map with matrix elements and their coordinates
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int key = mat[i][j]; // Matrix element
int[] val = new int[]{i, j}; // Coordinates (row, column) of the element
map.put(key, val); // Store in the map
}
}
// Arrays to count the number of elements marked in each row and column
int[] rowc = new int[m];
int[] colc = new int[n];
// Iterate over the elements in the array
for (int i = 0; i < arr.length; i++) {
int key = arr[i]; // Current element being marked
int[] loc = map.get(key); // Retrieve the coordinates of the element from the map
// Increment the count of marked elements in the respective row and column
rowc[loc[0]]++;
colc[loc[1]]++;
// Check if the current row or column is fully marked
if (rowc[loc[0]] == n || colc[loc[1]] == m) {
return i; // Return the current index if a row or column is completely marked
}
}
// Impossible to come here as per problem constraints
return -1;
}
}
```
```c++ []
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
unordered_map<int, pair<int, int>> map;
int m = mat.size(); // Number of rows
int n = mat[0].size(); // Number of columns
// Populate the map with matrix elements and their coordinates
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map[mat[i][j]] = {i, j};
}
}
// Arrays to count the number of elements marked in each row and column
vector<int> rowc(m, 0);
vector<int> colc(n, 0);
// Iterate over the elements in the array
for (int i = 0; i < arr.size(); i++) {
int key = arr[i];
auto loc = map[key]; // Retrieve the coordinates of the element
rowc[loc.first]++;
colc[loc.second]++;
// Check if the current row or column is fully marked
if (rowc[loc.first] == n || colc[loc.second] == m) {
return i;
}
}
return -1; // Return -1 if no row or column is fully marked
}
};
```
```python []
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
unordered_map<int, pair<int, int>> map;
int m = mat.size(); // Number of rows
int n = mat[0].size(); // Number of columns
// Populate the map with matrix elements and their coordinates
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map[mat[i][j]] = {i, j};
}
}
// Arrays to count the number of elements marked in each row and column
vector<int> rowc(m, 0);
vector<int> colc(n, 0);
// Iterate over the elements in the array
for (int i = 0; i < arr.size(); i++) {
int key = arr[i];
auto loc = map[key]; // Retrieve the coordinates of the element
rowc[loc.first]++;
colc[loc.second]++;
// Check if the current row or column is fully marked
if (rowc[loc.first] == n || colc[loc.second] == m) {
return i;
}
}
return -1; // Return -1 if no row or column is fully marked
}
};
```
LeetCode 2661 First Completely Painted Row or Column | Hash Table | Adobe Interview Question
https://youtu.be/6rY5YR0GOkU
| 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 1 |
first-completely-painted-row-or-column | JAVA CODE | java-code-by-ayeshakhan7-45yq | Code | ayeshakhan7 | NORMAL | 2025-01-20T09:19:39.559427+00:00 | 2025-01-20T09:19:39.559427+00:00 | 108 | false |
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n = mat.length; //rows
int m = mat[0].length; //cols
int rowCount[] = new int[n];
int colCount[] = new int[m];
// num -> (r,c)
HashMap<Integer,int[]> map = new HashMap<>();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
map.put(mat[i][j], new int[]{i,j});
}
}
int totalCells = n*m;
for(int i=0;i<totalCells;i++){
int cell[] = map.get(arr[i]);
rowCount[cell[0]]++;
colCount[cell[1]]++;
if(rowCount[cell[0]] == m || colCount[cell[1]] == n){
return i;
}
}
return -1;
}
}
``` | 3 | 0 | ['Java'] | 1 |
first-completely-painted-row-or-column | ✅ 🔥 Faster | Greedy | Beginner friendly ✅ 🔥 | faster-greedy-beginner-friendly-by-suren-0oeq | IntuitionTwo key thing to look upon is knowing the position of each element and finding whether a particular row or column is paintedApproach
Achieve the first | Surendaar | NORMAL | 2025-01-20T08:55:36.390093+00:00 | 2025-01-20T08:55:36.390093+00:00 | 72 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Two key thing to look upon is knowing the position of each element and finding whether a particular row or column is painted
# Approach
<!-- Describe your approach to solving the problem. -->
1. Achieve the first step by storing the index value of each item in an array called indexArray, where 1 -> [x][y], 2 -> [x][y], and so on.
2. You can determine if a row or column is painted by keeping track of a rowArray and a columnArray. Painting any cell in a row or column increases its corresponding value, and once it reaches n (for rows) or m (for columns), the value is returned.
# Complexity
- Time complexity: O(m x n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O (m x n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m = len(mat)
n = len(mat[0])
ln = len(arr)
index = [[0, 0] for _ in range(0, ln+1)]
row = [0] * m
col = [0] * n
for i in range (0, m):
for j in range (0, n):
val = mat[i][j]
index[val][0] = i
index[val][1] = j
res=0
for i in range (0, ln):
val = arr[i]
row[index[val][0]]+=1
col[index[val][1]]+=1
res+=1
if row[index[val][0]]==n or col[index[val][1]]==m:
return res-1
return res-1
``` | 3 | 0 | ['Greedy', 'Python3'] | 0 |
first-completely-painted-row-or-column | 🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏 | beats-super-easy-beginners-by-codewithsp-b6vg | IntuitionThe task is to find the first index in an array where marking a number in a given matrix results in a complete row or column being marked. My initial t | CodeWithSparsh | NORMAL | 2025-01-20T07:54:04.917571+00:00 | 2025-01-20T14:56:39.527721+00:00 | 293 | false | 
---
## Intuition
The task is to find the first index in an array where marking a number in a given matrix results in a complete row or column being marked. My initial thought is to track how many cells have been marked in each row and column, decrementing these counts as we process each number from the input array. Once a row or column reaches zero (indicating it has been fully marked), we can return the corresponding index.
## Approach
1. **Initialization**:
- Determine the number of rows (`r`) and columns (`c`) in the matrix.
- Create two lists (`row` and `col`) to keep track of how many cells are left to mark in each row and column, initialized to the total number of columns and rows, respectively.
- Create a 2D list (`position`) to map each number in the matrix to its corresponding row and column indices.
2. **Mapping Positions**:
- Populate the `position` list such that `position[number]` gives the coordinates of `number` in the matrix. This allows for quick lookups when processing the input array.
3. **Marking Cells**:
- Iterate through the input array (`arr`):
- For each number, retrieve its position from `position`.
- Decrement the count for the corresponding row and column.
- Check if either count reaches zero, indicating that the entire row or column has been marked.
- If a complete row or column is found, return the current index.
4. **Return Value**:
- If no complete row or column is found after processing all elements, return -1.
### Code Examples
```cpp []
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int r = mat.size();
int c = mat[0].size();
vector<int> row(r, c);
vector<int> col(c, r);
vector<vector<int>> position((r + 1) * (c + 1), vector<int>(2, 0));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
position[mat[i][j]] = {i, j};
}
}
int index = 0;
for (int n : arr) {
vector<int> pos = position[n];
int rowIdx = pos[0];
int colIdx = pos[1];
row[rowIdx]--;
col[colIdx]--;
if (row[rowIdx] == 0 || col[colIdx] == 0) return index;
index++;
}
return -1;
}
};
```
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int r = mat.length;
int c = mat[0].length;
int[] row = new int[r];
int[] col = new int[c];
// Initialize row and column counts
Arrays.fill(row, c);
Arrays.fill(col, r);
// Map to find positions of numbers in the matrix
int[][] position = new int[(r * c) + 1][2];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
position[mat[i][j]] = new int[]{i, j};
}
}
for (int index = 0; index < arr.length; index++) {
int number = arr[index];
int[] pos = position[number];
int rowIdx = pos[0];
int colIdx = pos[1];
// Decrement counts
row[rowIdx]--;
col[colIdx]--;
// Check if any row or column is completely marked
if (row[rowIdx] == 0 || col[colIdx] == 0) return index;
}
return -1; // If no complete row or column is found
}
}
```
```javascript []
class Solution {
firstCompleteIndex(arr, mat) {
const r = mat.length;
const c = mat[0].length;
const row = new Array(r).fill(c);
const col = new Array(c).fill(r);
const position = Array.from({ length: (r * c) + 1 }, () => [0, 0]);
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
position[mat[i][j]] = [i, j];
}
}
for (let index = 0; index < arr.length; index++) {
const number = arr[index];
const [rowIdx, colIdx] = position[number];
// Decrement counts
row[rowIdx]--;
col[colIdx]--;
// Check if any row or column is completely marked
if (row[rowIdx] === 0 || col[colIdx] === 0) return index;
}
return -1; // If no complete row or column is found
}
}
```
```python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
r = len(mat)
c = len(mat[0])
# Initialize counters for rows and columns
row_count = [c] * r
col_count = [r] * c
# Map to find positions of numbers in the matrix
position_map = [[0, 0] for _ in range((r * c) + 1)]
for i in range(r):
for j in range(c):
position_map[mat[i][j]] = [i, j]
# Iterate through arr and mark cells
for index in range(len(arr)):
number = arr[index]
pos = position_map[number]
row_idx, col_idx = pos
# Decrement counts
row_count[row_idx] -= 1
col_count[col_idx] -= 1
# Check if any row or column is completely marked
if row_count[row_idx] == 0 or col_count[col_idx] == 0:
return index
return -1 # If no complete row or column is found
```
```dart []
class Solution {
int firstCompleteIndex(List<int> arr, List<List<int>> mat) {
int r = mat.length;
int c = mat[0].length;
List<int> row = List.generate(r, (index) => c);
List<int> col = List.generate(c, (index) => r);
List<List<int>> position =
List.generate((r * c) + 1, (index) => [0, 0]);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
position[mat[i][j]] = [i, j];
}
}
int index = 0;
for (int n in arr) {
List<int> pos = position[n];
int rowIdx = pos[0];
int colIdx = pos[1];
// Decrement counts
row[rowIdx]--;
col[colIdx]--;
// Check if any row or column is completely marked
if (row[rowIdx] == 0 || col[colIdx] == 0) return index;
index++;
}
return -1; // If no complete row or column is found
}
}
```
## Complexity
- **Time complexity**: $$O(n + m \times p)$$ where:
- $$n$$ is the length of `arr`
- $$m$$ is the number of rows in `mat`
- $$p$$ is the number of columns in `mat`
This accounts for constructing `positionMap` and iterating through `arr`.
- **Space complexity**: $$O(m \times p)$$ where:
- $$m$$ is the number of rows in `mat`
- $$p$$ is the number of columns in `mat`
This accounts for storing `positionMap`, `rowCount`, and `colCount`.
## Citations
**Counting Rows and Columns**: This resource covers various methods to count elements across different dimensions within data structures [LeetCode Discuss](https://leetcode.com/discuss/general-discussion/460694/).
---
 {:style='width:250px'}
| 3 | 0 | ['Array', 'Hash Table', 'C', 'Matrix', 'C++', 'Java', 'Python3', 'JavaScript', 'Dart'] | 3 |
first-completely-painted-row-or-column | Very intuitive solution || Double Hashing || Must Learn || Please Upvote | very-intuitive-solution-double-hashing-m-tyvv | IntuitionMaintain the live count of elements in rows and columns. At index i in arr remove the element from the live counts.If the count of row or column become | Shiv19_03 | NORMAL | 2025-01-20T07:52:25.871698+00:00 | 2025-01-20T07:52:25.871698+00:00 | 33 | false | # Intuition
Maintain the live count of elements in rows and columns. At index i in arr remove the element from the live counts.If the count of row or column becomes 0 return the index i.
# Approach
Maintain a row, column hashmap the sotres count of numbers not yet seen in arr. If any row or column turns 0 return the current index of arr.
# Complexity
- Time complexity:
$$O(m.n)$$ --> The size of array is m.n.
- Space complexity:
$$O(n+m)$$ --> Creating the row, column hashmaps.
# Code
```python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
r,c = len(mat),len(mat[0])
rows = {x:c for x in range(r)}
cols = {x:r for x in range(c)}
m = defaultdict()
for i in range(r):
for j in range(c):
m[mat[i][j]] = (i,j)
for i in range(len(arr)):
row,col = m[arr[i]]
rows[row] -= 1
cols[col] -= 1
if rows[row] == 0 or cols[col] == 0:
return i
``` | 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python', 'Python3'] | 0 |
first-completely-painted-row-or-column | 🚀 Optimized Bingo Solver: Fast Tracking Rows & Columns with Flattened Positions 🎯 | optimized-bingo-solver-fast-tracking-row-33zp | IntuitionThe problem can be visualized as playing bingo, where we eliminate numbers from the matrix one by one. After each elimination, we need to check whether | Bulba_Bulbasar | NORMAL | 2025-01-20T07:20:35.512589+00:00 | 2025-01-20T07:20:35.512589+00:00 | 138 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem can be visualized as playing bingo, where we eliminate numbers from the matrix one by one. After each elimination, we need to check whether a complete row or column has been marked. Instead of repeatedly checking the entire row and column after every elimination (brute force), we can optimize the process by maintaining a count of marked cells for each row and column. Whenever the count for any row or column matches its respective length, we can immediately return the index.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Preprocess the Matrix: Use a HashMap to store the positions of each value in the matrix. This allows O(1) lookup for the position of any value in arr.
2. Track Row and Column Counts: Maintain a freq array where:
- freq[i][0] tracks the number of marked cells in the i-th row.
- freq[j][1] tracks the number of marked cells in the j-th column.
3. Iterate Through the Input Array:
- For each value in arr, find its position in the matrix using the preprocessed HashMap.
- Update the counts for the corresponding row and column in the freq array.
- Check if the count for any row or column matches its respective length (n for rows and m for columns). If so, return the index of the current value in arr.
4. Return Result: If no row or column is completely marked after processing all elements, return −1.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(m*n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(m*n)
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length; // Number of rows in the matrix
int n = mat[0].length; // Number of columns in the matrix
// Initialize a frequency array to track the count of marked cells for rows and columns.
int[][] freq = new int[Math.max(m, n)][2];
// Create a HashMap to store the positions of each value in the matrix.
HashMap<Integer, int[]> map = new HashMap<>();
// Populate the HashMap with the positions of values in the matrix.
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map.put(mat[i][j], new int[]{i, j});
}
}
// Iterate over the elements of the input array `arr`.
for (int i = 0; i < arr.length; i++) {
// Get the position of the current element in the matrix using the HashMap.
int[] pos = map.get(arr[i]);
int x = pos[0]; // Row index of the element in the matrix
int y = pos[1]; // Column index of the element in the matrix
// Increment the count for the corresponding row and column.
freq[x][0]++; // Increment count for the row
freq[y][1]++; // Increment count for the column
// Check if the current row or column is completely marked.
if (freq[x][0] == n || freq[y][1] == m) {
return i; // Return the index of the current element in `arr`.
}
}
// If no row or column is completely marked, return -1.
return -1;
}
}
```
---
---
# Further Optimization
To optimize the solution further, we can eliminate the need for a 2D frequency array (freq) by using two 1D arrays to directly track the counts of rows and columns. Additionally, instead of storing a HashMap with full matrix coordinates, we can preprocess the matrix into a flattened 1D array. This eliminates the overhead of storing the entire mapping and allows faster lookups by directly indexing into the flattened array.
# Optimized Approach
1. Flatten the Matrix:
We can flatten the mat into a 1D array flatPos such that the value at flatPos[val] gives the row and column indices of the value val.
For a value val in mat[i][j], store flatPos[val] = i * n + j.
- This allows us to calculate the row index as row = flatPos[val] / n and the column index as col = flatPos[val] % n.
2. Use Separate Count Arrays for Rows and Columns:
Instead of maintaining a 2D array for counts, use two 1D arrays:
- rowCount of size m to track the number of marked cells in each row.
- colCount of size n to track the number of marked cells in each column.
3. Process the Array arr in Order:
- For each value in arr, compute its row and column indices from flatPos.
- Update the respective counts in rowCount and colCount.
- Check if any count reaches the required size (n for rows, m for columns), and return the index if it does.
4. Early Exit:
- As soon as a row or column is completely marked, exit early without processing further elements.
---
# Optimized Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length; // Number of rows
int n = mat[0].length; // Number of columns
int totalCells = m * n;
// Step 1: Flatten the matrix into a position array
int[] flatPos = new int[totalCells + 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
flatPos[mat[i][j]] = i * n + j; // Store flattened position
}
}
// Step 2: Initialize row and column count arrays
int[] rowCount = new int[m];
int[] colCount = new int[n];
// Step 3: Process each number in the array
for (int i = 0; i < arr.length; i++) {
int pos = flatPos[arr[i]];
int row = pos / n; // Extract row index
int col = pos % n; // Extract column index
// Increment the counts for the row and column
rowCount[row]++;
colCount[col]++;
// Check if any row or column is completely marked
if (rowCount[row] == n || colCount[col] == m) {
return i; // Return the index
}
}
// If no row or column is completely marked, return -1
return -1;
}
}
```
---

| 3 | 0 | ['Array', 'Hash Table', 'Java'] | 2 |
first-completely-painted-row-or-column | Beats 100% , Simple JAVA Solution without Map | beats-100-simple-java-solution-without-m-muzu | IntuitionIterate through matrix and keep track of maximum index in a row and a column. Return minimum of all maximum indexes.
In simple words, find maximum inde | parr_ot | NORMAL | 2025-01-20T06:35:36.188790+00:00 | 2025-01-20T06:35:36.188790+00:00 | 50 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Iterate through matrix and keep track of maximum index in a row and a column. Return minimum of all maximum indexes.
In simple words, find maximum index (acc. to "arr" array) in all rows and columns and then return minimum among them.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(m*n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(m*n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length, n = mat[0].length;
int[] hash = new int[m * n + 1];
int ans = m * n;
for (int i = 0; i < arr.length; i++)
hash[arr[i]] = i;
for (int i = 0; i < m; i++) {
int index = -1;
for (int j = 0; j < n; j++) {
index = Math.max(index, hash[mat[i][j]]);
}
ans = Math.min(ans, index);
}
for (int i = 0; i < n; i++) {
int index = -1;
for (int j = 0; j < m; j++) {
index = Math.max(index, hash[mat[j][i]]);
}
ans = Math.min(ans, index);
}
return ans;
}
}
``` | 3 | 0 | ['Hash Table', 'Java'] | 0 |
first-completely-painted-row-or-column | Easy solution | easy-solution-by-kiran_kommanaboyina-qnne | IntuitionThe problem requires determining the first index in the array arr at which either a row or a column in the matrix mat is completely filled. The key obs | kiran_kommanaboyina | NORMAL | 2025-01-20T05:23:26.185942+00:00 | 2025-01-20T05:23:26.185942+00:00 | 34 | false | # Intuition
The problem requires determining the first index in the array arr at which either a row or a column in the matrix mat is completely filled. The key observation is that we can track the fill count of rows and columns as we iterate through arr and check if any row or column reaches its full size.
# Approach
Mapping Matrix Values to Indices:
Use a HashMap to store the row and column indices for each value in the matrix mat. This enables quick lookups of the position of any number in mat.
Tracking Row and Column Counts:
Use two arrays:
rows[] to store the count of filled cells for each row.
cols[] to store the count of filled cells for each column.
Iterate Through the Array arr:
For each element in arr, get its position (row and column) from the HashMap.
Increment the corresponding row and column counters.
Check if the row or column is completely filled (i.e., the count equals the number of columns or rows, respectively).
If a row or column is fully filled, return the current index of arr.
Return Default Value:
If no row or column is completely filled by the end of the iteration, return 0 as specified in the code.
# Complexity
- Time complexity:
Precomputing Matrix Indices: O(n×m), where n is the number of rows and m is the number of columns in the matrix.
Processing Array arr: O(k), where k is the length of arr.
Overall Complexity: O(n×m+k).
- Space complexity:
HashMap to store matrix positions: O(n×m).
Arrays rows[] and cols[]: O(n+m).
Overall Complexity: O(n×m).
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n=mat.length;
int m=mat[0].length;
int rows[]=new int[n];
int cols[]=new int[m];
HashMap<Integer,ArrayList<Integer>> hm=new HashMap<>();
for(int i=0;i<mat.length;i++){
for(int j=0;j<mat[0].length;j++){
ArrayList<Integer> list=new ArrayList<>();
list.add(i);
list.add(j);
hm.put(mat[i][j],list);
}
}
for(int i=0;i<arr.length;i++){
int ind1=hm.get(arr[i]).get(0);
int ind2=hm.get(arr[i]).get(1);
rows[ind1]++;
cols[ind2]++;
if(rows[ind1]>=m)
return i;
if(cols[ind2]>=n)
return i;
}
return 0;
}
}
``` | 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | First Completely Painted Row or column | first-completely-painted-row-or-column-b-lt9k | Code | sandeepvaiml | NORMAL | 2025-01-20T04:35:06.663064+00:00 | 2025-01-20T04:35:06.663064+00:00 | 6 | false |
# Code
```python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
pos = {}
for i in range(len(mat)):
for j in range(len(mat[0])):
pos[mat[i][j]] = (i, j)
row_count=[0]*len(mat)
col_count=[0] * len(mat[0])
for idx,num in enumerate(arr):
if num in pos:
r,c=pos[num]
row_count[r]+=1
col_count[c]+=1
if row_count[r]==len(mat[0]) or col_count[c]==len(mat):
return idx
``` | 3 | 0 | ['Python3'] | 0 |
first-completely-painted-row-or-column | Beats 100% | Very Easy solution | C++ Java Python | beats-100-very-easy-solution-c-java-pyth-2ha3 | IntuitionThe goal is to find the first index in the array arr such that marking the cells corresponding to the indices in arr completely fills either a row or a | B_I_T | NORMAL | 2025-01-20T04:16:54.278194+00:00 | 2025-01-20T04:16:54.278194+00:00 | 114 | false | 
# Intuition
The goal is to find the first index in the array arr such that marking the cells corresponding to the indices in arr completely fills either a row or a column in the matrix mat. This is done by tracking the remaining unmarked cells in each row and column.
# Approach
1. Position Mapping:
- First, map each value in the matrix mat to its corresponding position (row and column indices). This allows us to efficiently access the position of any value in constant time during traversal.
2. Tracking Row and Column Completion:
- Maintain two arrays, rowSum and colSum, initialized to the size of the columns and rows respectively. These arrays represent how many unmarked cells are left in each row and column.
- Initially, rowSum[j] = n for each column j, and colSum[i] = m for each row i, as no cells are marked at the beginning.
3. Simulate the Marking Process:
- Iterate through the array arr, marking the corresponding cell in mat for each value.
- Decrement the counts in the rowSum and colSum arrays for the respective row and column.
- Check if the marking of the current cell completes a row (rowSum[y] == 0) or column (colSum[x] == 0). If so, return the index in arr as the result.
4. Edge Case:
- If no row or column is completely filled by the end of the array, return -1.
# Complexity
- Time Complexity : O(n⋅m+len(arr)).
- Space Complexity : O(n⋅m).
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n=mat.size(),m=mat[0].size();
vector<int> position(n*m);
vector<int> colSum(n,m),rowSum(m,n);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
position[mat[i][j]-1] = i*m+j;
}
}
for(int i=0; i<arr.size(); i++){
int ind = position[arr[i]-1],
x = ind/m, y = ind%m;
rowSum[y]--;
colSum[x]--;
if(rowSum[y] == 0 || colSum[x] == 0) return i;
}
return -1;
}
};
```
```Java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n = mat.length, m = mat[0].length;
int[] position = new int[n * m];
int[] rowSum = new int[m];
int[] colSum = new int[n];
Arrays.fill(rowSum, n);
Arrays.fill(colSum, m);
// Map matrix values to their positions
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
position[mat[i][j] - 1] = i * m + j;
}
}
// Process the marking based on arr
for (int i = 0; i < arr.length; i++) {
int ind = position[arr[i] - 1];
int x = ind / m, y = ind % m;
rowSum[y]--;
colSum[x]--;
if (rowSum[y] == 0 || colSum[x] == 0) {
return i;
}
}
return -1;
}
}
```
```Python []
class Solution:
def firstCompleteIndex(self, arr, mat):
n, m = len(mat), len(mat[0])
position = [0] * (n * m)
rowSum = [n] * m
colSum = [m] * n
# Map matrix values to their positions
for i in range(n):
for j in range(m):
position[mat[i][j] - 1] = i * m + j
# Process the marking based on arr
for i, value in enumerate(arr):
ind = position[value - 1]
x, y = divmod(ind, m)
rowSum[y] -= 1
colSum[x] -= 1
if rowSum[y] == 0 or colSum[x] == 0:
return i
return -1
```

| 3 | 0 | ['Array', 'Hash Table', 'Math', 'Matrix', 'Python', 'C++', 'Java'] | 0 |
first-completely-painted-row-or-column | C# Solution for First Completely Painted Row or Column Problem | c-solution-for-first-completely-painted-rj4lc | IntuitionThe problem involves identifying the first step where either a row or a column in the matrix mat is completely painted, based on the order defined in t | Aman_Raj_Sinha | NORMAL | 2025-01-20T04:14:51.082886+00:00 | 2025-01-20T04:14:51.082886+00:00 | 80 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem involves identifying the first step where either a row or a column in the matrix mat is completely painted, based on the order defined in the array arr.
Key observations:
1. Every integer in the matrix mat is unique and appears exactly once in arr. This allows us to use a mapping for efficient lookups.
2. Painting a cell corresponds to marking its row and column as “painted.”
3. The first row or column to reach its total cell count (n for rows or m for columns) is the solution.
Thus, we can efficiently simulate the painting process while keeping track of painted cells in each row and column.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Mapping Elements:
• Create a dictionary to map each integer in mat to its (row, col) coordinates. This ensures O(1) lookups for any number in arr.
2. Tracking Painted Cells:
• Use two arrays:
• rowPaintCounts of size m to track the number of painted cells in each row.
• colPaintCounts of size n to track the number of painted cells in each column.
3. Painting Simulation:
• Iterate through arr, and for each integer:
• Look up its (row, col) position in mat using the dictionary.
• Increment the counts for the corresponding row and column.
• Check if the row or column becomes fully painted.
• Return the current index if either condition is met.
4. Efficiency:
• By leveraging a dictionary for lookups and arrays for tracking counts, we ensure efficient processing.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
1. Mapping Elements:
• Constructing the dictionary from mat requires visiting each cell in the matrix exactly once. This takes O(m * n).
2. Processing arr:
• We iterate through arr (of size m * n) and perform O(1) operations (dictionary lookups, updates, and checks) for each element. This takes O(m * n).
Overall Time Complexity: O(m * n).
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1. Dictionary:
• The dictionary stores m * n key-value pairs, where each key is an integer and the value is a 2-element tuple (row, col). This takes O(m * n).
2. Row and Column Arrays:
• Two arrays are used: rowPaintCounts of size m and colPaintCounts of size n. This takes O(m + n).
Overall Space Complexity: O(m * n).
# Code
```csharp []
public class Solution {
public int FirstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.Length; // Number of rows
int n = mat[0].Length; // Number of columns
// Map to store the position of each number in the matrix
Dictionary<int, (int row, int col)> positionMap = new Dictionary<int, (int row, int col)>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
positionMap[mat[i][j]] = (i, j);
}
}
int[] rowPaintCounts = new int[m];
int[] colPaintCounts = new int[n];
for (int i = 0; i < arr.Length; i++) {
(int row, int col) = positionMap[arr[i]];
rowPaintCounts[row]++;
colPaintCounts[col]++;
if (rowPaintCounts[row] == n || colPaintCounts[col] == m) {
return i;
}
}
return -1;
}
}
``` | 3 | 0 | ['C#'] | 0 |
first-completely-painted-row-or-column | 0ms | Beats 100% | Efficient Java Solution | Using Hash Mapping with Simulation | Full Explanation | 0ms-beats-100-efficient-java-solution-us-2ggc | YouTubeIntuitionThe problem revolves around finding the earliest index at which a row or column in the matrix is fully painted. To do this efficiently
1. Use a | rahulvijayan2291 | NORMAL | 2025-01-20T02:58:50.794189+00:00 | 2025-01-20T06:45:52.514901+00:00 | 99 | false | 
## YouTube
https://youtu.be/jfwHLz25pfY
# Intuition
The problem revolves around finding the earliest index at which a row or column in the matrix is fully painted. To do this efficiently
1. Use a mapping of values in the array arr to their indices to avoid repeated searches.
2. Traverse through the matrix rows and columns, determining the maximum index needed to paint each row or column.
3. Track the minimum of these maximum indices, as this represents the earliest index when a row or column is fully painted.
# Approach
1. Mapping Array Values to Indices:
- Create a `map` array where `map[x]` gives the index of `x` in the input array `arr`. This allows O(1) lookup for the index of any value in `arr`.
2. Processing Rows:
- For each row in the matrix, determine the maximum index in `arr` of the elements in that row. This index represents when the row is fully painted.
- Update the result `ans` with the smallest maximum index found across rows.
3. Processing Columns:
- Similarly, for each column in the matrix, determine the maximum index in `arr` of the elements in that column.
- Update `ans` with the smallest maximum index found across columns.
4. Returning the Result:
- After processing all rows and columns, return the smallest index (`ans`) where a row or column is fully painted.
# Complexity
- Time complexity:
- Creating the map array: $$O(n)$$, where `n` is the size of `arr`.
- Processing rows: $$O(m⋅n)$$, where `m` is the number of rows and `n` is the number of columns in the matrix.
- Processing columns: $$O(m⋅n)$$.
- Total: $$O(m⋅n)$$.
- Space complexity:
- The map array requires $$O(n)$$ space.
- Total: $$O(n)$$
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int[] map = new int[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
map[arr[i]] = i;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < mat.length; i++) {
int max = 0;
for (int j = 0; j < mat[i].length; j++) {
max = Math.max(max, map[mat[i][j]]);
}
ans = Math.min(ans, max);
}
for (int i = 0; i < mat[0].length; i++) {
int max = 0;
for (int j = 0; j < mat.length; j++) {
max = Math.max(max, map[mat[j][i]]);
}
ans = Math.min(ans, max);
}
return ans;
}
}
``` | 3 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | C++ 🔥||Easy Solution 🎯|| Beginner Friendly⭐||Hash Table💪🏻 | c-easy-solution-beginner-friendlyhash-ta-99vi | IntuitionThe problem involves finding the first index at which either a row or column in the matrix is completely marked. Since we need to determine the earlies | pranay_20 | NORMAL | 2025-01-20T02:43:09.046849+00:00 | 2025-01-20T02:43:09.046849+00:00 | 73 | false |
# Intuition
The problem involves finding the first index at which either a row or column in the matrix is completely marked. Since we need to determine the earliest index, it makes sense to map each matrix element to its respective row and column indices. Using this mapping, we can track the count of marked elements for each row and column as we iterate through the given array `arr`.
# Approach
1. **Mapping Elements to Indices**:
- Create two hash maps, `row` and `col`, to store the row and column indices of each element in `mat`.
2. **Tracking Counts**:
- Maintain two arrays, `r` and `c`, to count the number of marked elements for each row and column.
3. **Iterating Through `arr`**:
- For each element in `arr`, update the respective row and column counts.
- If a row or column becomes completely marked (i.e., count equals the number of elements in that row/column), return the current index.
4. **Return the Result**:
- If no row or column is fully marked during the iteration, return the last possible index.
# Complexity
- **Time Complexity**:
$$O(m \times n)$$
- Building the `row` and `col` maps requires iterating through the entire matrix once.
- Processing `arr` also takes $$O(m \times n)$$ since it contains all the elements of the matrix.
- **Space Complexity**:
$$O(m + n + m \times n)$$
- The `row` and `col` maps store each element of the matrix.
- The `r` and `c` arrays require $$O(m)$$ and $$O(n)$$ space, respectively.
# Code
```cpp
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
unordered_map<int, int> row, col;
int m = mat.size();
int n = mat[0].size();
// Map each matrix element to its row and column indices
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
row[mat[i][j]] = i;
col[mat[i][j]] = j;
}
}
vector<int> r(m, 0), c(n, 0); // Count of marked elements for rows and columns
// Process the elements in arr
for (int i = 0; i < m * n; i++) {
int num = arr[i];
r[row[num]]++; // Increment row count
if (r[row[num]] == n) return i; // Check if row is complete
c[col[num]]++; // Increment column count
if (c[col[num]] == m) return i; // Check if column is complete
}
return m * n - 1; // Return the last index if no row/column is fully marked
}
};
``` | 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Map with Optimized Checking - O(N*M) | map-with-optimized-checking-onm-by-chrom-4eht | SolutionOverviewWe are given an m×n matrix mat and an array arr of length m∗n both containing every integer from [1,m∗n].Starting from index i = 0, mark the val | chromaa | NORMAL | 2024-12-24T17:32:17.877787+00:00 | 2024-12-24T17:56:33.910212+00:00 | 137 | false | # Solution
---
## Overview
We are given an $m \times n$ matrix `mat` and an array `arr` of length $m * n$ both containing every integer from $[1, m * n]$.
Starting from index `i = 0`, mark the value `arr[i]` as seen in `mat`. Return the smallest index where either a row or column is fully seen.
---
## Approach 1: Map with Brute Force Checking (TLE)
### Intuition
Starting from index `i = 0`, we mark the value `arr[i]` as seen in `mat`. To be more efficient, we use a map to get the row and column of the value in `mat`.
To mark the value `arr[i]` as seen, we multiply `arr[i]` by $-1$. Now if any row or column is completely seen, we can return the current index $i$. We only need to check the row and column that `arr[i]` is in, because this is the only row and column that is being modified at this iteration. If any value in the row or column is positive, this means we have not seen the full row or column yet.
### Algorithm
- Initialize `R` as the number of rows and `C` as the number of columms in `mat` and initialize a map `m`
- For all rows `row` and all columns `col`, set the value `mat[row][col]` to the position `[row, column]` in the map `m`
- For every index $i$:
- Let `value` be the value of `arr[i]`
- Get the row and column index, `row` and `col` from `m`, that is, `m[value]`
- Mark the row and column as seen, that is, `mat[row][col] = -mat[row][col]`
- If the row or column is fully seen:
- Return $i$
### Implementation
```python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
def checkRow(row: int) -> bool:
""" return true if row is completely seen """
for col in range(C):
if mat[row][col] > 0:
return False
return True
def checkColumn(col: int) -> bool:
""" return true if col is completely seen """
for row in range(R):
if mat[row][col] > 0:
return False
return True
R, C = len(mat), len(mat[0])
m = {}
for row in range(R):
for col in range(C):
value = mat[row][col]
m[value] = [row, col]
for index, val in enumerate(arr):
row, col = m[val]
mat[row][col] = -mat[row][col] # mark as seen
if checkRow(row) or checkColumn(col): # if completely seen
return index
return -1
```
```C++ []
class Solution {
public:
bool checkRow(int row, vector<vector<int>>& mat) {
// return true if row is completely seen
for (int col = 0; col < mat[0].size(); col++) {
if (mat[row][col] > 0) {
return false;
}
}
return true;
}
bool checkColumn(int col, vector<vector<int>>& mat) {
// return true if col is completely seen
for (int row = 0; row < mat.size(); row++) {
if (mat[row][col] > 0) {
return false;
}
}
return true;
}
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int R = mat.size(), C = mat[0].size();
unordered_map<int, pair<int, int>> m;
for (int row = 0; row < R; row++) {
for (int col = 0; col < C; col++) {
int value = mat[row][col];
m[value] = {row, col};
}
}
for (int index = 0; index < arr.size(); index++) {
int val = arr[index];
auto [row, col] = m[val];
mat[row][col] = -mat[row][col]; // mark as seen
if (checkRow(row, mat) || checkColumn(col, mat)) { // if completely seen
return index;
}
}
return -1;
}
};
```
### Complexity Analysis
Let $m$ be the number of rows, and $n$ be the number of columns in the matrix.
- Time complexity: $O\left( m * n * (m + n) \right) \newline$
In the worst case, this approach iterates through approximately all $m * n$ elements. For each element, in the worst case we have to iterate over the row and column, which is of size $m + n$.
- Space complexity: $O\left( m * n \right) \newline$
The only additional space we are using is the map, which stores $m * n$ elements.
---
## Approach 2: Map with Optimized Checking
### Intuition
The previous approach has a time complexity of $O\left( m * n * (m + n) \right)$. To improve the time complexity, instead of iterating over the row and column each time, we maintain the count of how many elements we have seen in each row and column using two arrays.
### Algorithm
- Initialize `R` as the number of rows and `C` as the number of columms in `mat` and initialize a map `m`
- Initialize `rows` and `cols` as arrays to store how many seen elements are in each row and column
- For all rows `row` and all columns `col`, set the value `mat[row][col]` to the position `[row, column]` in the map `m`
- For every index $i$:
- Let `value` be the value of `arr[i]`
- Get the row and column index, `row` and `col` from `m`, that is, `m[value]`
- Mark the row and column as seen, that is, `rows[row] += 1` and `cols[col] += 1`
- If the row or column is fully seen, that is, if `rows[row] == C` or `cols[col] == R`:
- Return $i$
### Implementation
```python3 []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
R, C = len(mat), len(mat[0])
rows = [0] * R
cols = [0] * C
m = {}
for row in range(R):
for col in range(C):
value = mat[row][col]
m[value] = [row, col]
for index, val in enumerate(arr):
row, col = m[val]
rows[row] += 1 # mark row as seen
cols[col] += 1 # mark col as seen
if rows[row] == C or cols[col] == R: # if completely seen
return index
return -1
```
```C++ []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int R = mat.size(), C = mat[0].size();
vector<int> rows(R), cols(C);
unordered_map<int, pair<int, int>> m;
for (int row = 0; row < R; row++) {
for (int col = 0; col < C; col++) {
int value = mat[row][col];
m[value] = {row, col};
}
}
for (int index = 0; index < arr.size(); index++) {
int val = arr[index];
auto [row, col] = m[val];
rows[row]++; // mark row as seen
cols[col]++; // mark col as seen
if (rows[row] == C || cols[col] == R) { // if completely seen
return index;
}
}
return -1;
}
};
```
### Complexity Analysis
Let $m$ be the number of rows, and $n$ be the number of columns in the matrix.
- Time complexity: $O\left( m * n \right) \newline$
In the worst case, this approach iterates through approximately all $m * n$ elements. For each element, we perform constant time operations.
- Space complexity: $O\left( m * n \right) \newline$
We are using a map which stores $m * n$ elements and two arrays of length $m$ and $n$. Therefore the space is dominated by $m * n$.
| 3 | 0 | ['Array', 'Hash Table', 'Matrix', 'Python3'] | 0 |
first-completely-painted-row-or-column | Simple C++ Solution | simple-c-solution-by-imdhruba-20dw | \nclass Solution {\n \npublic:\n void put(vector<vector<int>>& mat, unordered_map<int, vector<int>> &mpp){\n \n for(int i = 0; i < mat.size( | ImDhruba | NORMAL | 2023-12-14T09:12:20.273704+00:00 | 2023-12-14T09:12:20.273723+00:00 | 9 | false | ```\nclass Solution {\n \npublic:\n void put(vector<vector<int>>& mat, unordered_map<int, vector<int>> &mpp){\n \n for(int i = 0; i < mat.size(); i++){\n for(int j = 0; j < mat[0].size(); j++){\n \n vector<int> indexes {i,j};\n mpp[mat[i][j]] = indexes;\n }\n }\n }\n \npublic:\n vector<int> find(int val, unordered_map<int, vector<int>> &mpp){\n return mpp[val];\n }\n \npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n \n int noOfRows = mat.size(), noOfCols = mat[0].size();\n vector<int> rows(noOfRows,0), cols(noOfCols, 0);\n \n unordered_map<int, vector<int>> mpp;\n put(mat, mpp);\n \n for(int i = 0; i < arr.size(); i++){\n \n int val = arr[i];\n \n vector<int> rowCol = find(val, mpp);\n \n rows[rowCol[0]] += 1;\n cols[rowCol[1]] += 1;\n \n if(rows[rowCol[0]] == noOfCols || cols[rowCol[1]] == noOfRows){\n return i;\n }\n \n \n }\n \n return -1;\n }\n};\n``` | 3 | 0 | ['C'] | 0 |
first-completely-painted-row-or-column | Brute Force to Optimal | Easy to Understand | brute-force-to-optimal-easy-to-understan-7fnk | \n//Brute Force :- O(n^2) (will give TLE)\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int m=m | neel200 | NORMAL | 2023-05-01T05:42:59.085041+00:00 | 2023-05-01T06:01:28.583611+00:00 | 263 | false | ```\n//Brute Force :- O(n^2) (will give TLE)\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int m=mat.size(), n=mat[0].size(), size=arr.size(), idx=0;\n unordered_set<int>st;\n unordered_map<int, pair<int,int>>mp;\n \n for(int i=0;i<m;i++) {\n for(int j=0;j<n;j++) {\n mp[mat[i][j]]={i,j};\n }\n }\n while(idx < size) {\n st.insert(arr[idx]);\n auto it = mp.find(arr[idx]);\n int i=(it->second).first, j=(it->second).second;\n bool valid1=true,valid2=true;\n \n for(int col=0;col<n;col++) {\n if(st.find(mat[i][col]) == st.end()) {\n valid1=false;\n break;\n }\n\n }\n \n for(int row=0;row<m;row++) {\n if(st.find(mat[row][j]) == st.end()) {\n valid2=false;\n break;\n }\n\n }\n if(valid2 || valid1)return idx;\n\n idx++;\n }\n return -1;\n }\n};\n\n//Optimal :- O(m*n)\n\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n unordered_map<int,int>mp;\n int maxIdx = 0, m = mat.size(), n = mat[0].size(), res = INT_MAX;\n for(int i=0;i<arr.size();i++)\n mp[arr[i]]=i;\n \n for(int i=0;i<m;i++) {\n maxIdx = 0;\n for(int j=0;j<n;j++) {\n maxIdx = max(maxIdx, mp[mat[i][j]]);\n }\n res = min(res, maxIdx);\n }\n for(int i=0;i<n;i++) {\n maxIdx = 0;\n for(int j=0;j<m;j++) {\n maxIdx = max(maxIdx, mp[mat[j][i]]);\n }\n res = min(res, maxIdx);\n }\n return res;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
first-completely-painted-row-or-column | 🔥🔥 Accepted || ✅✅ C++ Solution with complete explanation using map. || 100% successful 🔥🔥 | accepted-c-solution-with-complete-explan-whe0 | Approach\n Describe your approach to solving the problem. \nFirst, we store all the elements of mat in map with its elements as key and their indexes as value. | Sanjeev_PU | NORMAL | 2023-04-30T08:53:21.001510+00:00 | 2023-04-30T08:57:02.560829+00:00 | 450 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, we store all the elements of $$mat$$ in $$map$$ with its elements as key and their indexes as value. (We are storing to reduce the search complexity in matrix).\n\nWe create two more vector to store the count of the elements painted in the particular column and row. We named the vector as $$rowCount$$ and $$colCount$$.\n\nNow, we traversal through the $$arr$$ and check the row and column of that element in $$mat$$ using the $$map$$ we created.\n\nNow, further we increment the colCount for columnIndex and rowCount for the rowIndex respectively.\n\nNext, we check if the $$colCount$$ is at its max (the max of column can be the number of the i.e $$n$$). Incase, we set the value of $$ans$$ variable as the current Index and break the loop.\nSimilarly, we check for $$rowCount$$ (for row max count will be the number of column i.e $$m$$).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nFirst, $$O(n*m)$$ for storing elements and their corresponding indexes in map. Second, $$O(n*m)$$ for traversing of arr.\nSo, overall time complexity is:\n$$O(2*n*m)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n*m)$$ for map\n$$O(n)$$ for rowCount.\n$$O(m)$$ for colCount.\nSo, overall space complexity is:\n$$O(n*m + (n+m))$$\n\n# Code\n```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int n = mat.size();\n int m = mat[0].size();\n map<int,pair<int,int>> mp;\n for(int i= 0; i<n; i++){\n for(int j = 0; j<m; j++){\n mp[mat[i][j]] = {i,j};\n }\n }\n \n vector<int> colCount(m,0);\n vector<int> rowCount(n,0);\n int ans = INT_MAX;\n for(int i = 0; i<m*n; i++){\n auto pr = mp[arr[i]];\n colCount[pr.second]++;\n rowCount[pr.first]++;\n \n if(colCount[pr.second] == n && ans > i){\n ans = i;\n break;\n }\n \n if(rowCount[pr.first] == m && ans > i){\n ans = i;\n break;\n }\n }\n \n return ans;\n }\n};\n``` | 3 | 0 | ['Ordered Map', 'C++'] | 0 |
first-completely-painted-row-or-column | Go || My solution | go-my-solution-by-wild-boar-725o | Complexity\n- Time complexity: O(n.m) \n- Space complexity: O(n.m) \n\n# Code\n\nfunc firstCompleteIndex(arr []int, mat [][]int) int {\n\tn, m := len(mat), len( | Wild-Boar | NORMAL | 2023-04-30T07:18:24.717269+00:00 | 2023-04-30T07:36:55.367425+00:00 | 155 | false | # Complexity\n- Time complexity: $$O(n.m)$$ \n- Space complexity: $$O(n.m)$$ \n\n# Code\n```\nfunc firstCompleteIndex(arr []int, mat [][]int) int {\n\tn, m := len(mat), len(mat[0])\n\trow := make([]int, n)\n\tcol := make([]int, m)\n\thm := make(map[int][2]int)\n\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j < m; j++ {\n\t\t\thm[mat[i][j]] = [2]int{i, j}\n\t\t}\n\t}\n\n\tfor i := 0; i < len(arr); i++ {\n\t\tk := hm[arr[i]]\n\t\trow[k[0]]++\n\t\tif row[k[0]] == m {\n\t\t\treturn i\n\t\t}\n\n\t\tcol[k[1]]++\n\t\tif col[k[1]] == n {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n``` | 3 | 0 | ['Go'] | 1 |
first-completely-painted-row-or-column | EASY TO UNDERSTAND || C++ || SIMPLE SOLUTION | easy-to-understand-c-simple-solution-by-2hn30 | \nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int a = mat.size(),b = mat[0].size(),c = arr.size | yash___sharma_ | NORMAL | 2023-04-30T04:07:19.186880+00:00 | 2023-04-30T04:07:19.186947+00:00 | 434 | false | ````\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int a = mat.size(),b = mat[0].size(),c = arr.size();\n vector<int> r1(a,0),c1(b,0);\n vector<vector<int>> ind(a*b+1);\n for(int i = 0; i < a; i++){\n for(int j = 0; j < b; j++){\n ind[mat[i][j]] = {i,j};\n }\n }\n // for(int k = 0; k < c; k++){\n // cout<<arr[k]<<" "<<ind[arr[k]][0]<<" "<<ind[arr[k]][1]<<endl;\n // }\n for(int k = 0; k < c; k++){\n r1[ind[arr[k]][0]]++;\n c1[ind[arr[k]][1]]++;\n // cout<<arr[k]<<" "<<ind[arr[k]][0]<<" "<<r1[ind[arr[k]][0]]<<" "<<ind[arr[k]][1]<<" "<<c1[ind[arr[k]][1]]<<endl;\n if(r1[ind[arr[k]][0]]==b)return k;\n if(c1[ind[arr[k]][1]]==a)return k;\n }\n return -1;\n }\n};\n```` | 3 | 0 | ['Hash Table', 'C', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Java | Simple solution | java-simple-solution-by-judgementdey-qnxe | Complexity\n- Time complexity: O(mn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(mn)\n Add your space complexity here, e.g. O(n) \n\n# | judgementdey | NORMAL | 2023-04-30T04:05:17.454007+00:00 | 2023-04-30T05:37:25.536267+00:00 | 181 | false | # Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n var m = mat.length;\n var n = mat[0].length;\n \n var rows = new int[m];\n var cols = new int[n];\n \n var map = new int[m*n][2];\n \n for (var i=0; i<m; i++) {\n for (var j=0; j<n; j++) {\n var a = mat[i][j] - 1;\n\n map[a][0] = i;\n map[a][1] = j;\n }\n }\n for (var i=0; i < arr.length; i++) {\n var a = arr[i] - 1;\n\n rows[map[a][0]]++;\n cols[map[a][1]]++;\n \n if (rows[map[a][0]] == n || cols[map[a][1]] == m)\n return i;\n } \n return m*n;\n }\n}\n```\nIf you like my solution, please upvote it! | 3 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | Derive Intuition through Paper & Pen | derive-intuition-through-paper-pen-by-sh-y0sv | Code | shivanigam | NORMAL | 2025-01-20T22:04:46.851790+00:00 | 2025-01-20T22:04:46.851790+00:00 | 9 | false | 
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < mat.length; i++) {
int max = -1;
for (int j = 0; j < mat[0].length; j++) {
int ind = map.get(mat[i][j]);
max = Math.max(ind, max);
}
min = Math.min(max, min);
}
for (int i = 0; i < mat[0].length; i++) {
int max = -1;
for (int j = 0; j < mat.length; j++) {
int ind = map.get(mat[j][i]);
max = Math.max(ind, max);
}
min = Math.min(max, min);
}
return min;
}
}
``` | 2 | 0 | ['Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | 🔥 Java | Early Exit Optimization 🚀 | Beats 100% | Efficient HashMap Use | LeetCode #2661 | java-early-exit-optimization-beats-100-e-fyo9 | 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 | yash_jain15 | NORMAL | 2025-01-20T19:07:16.352871+00:00 | 2025-01-20T19:07:16.352871+00:00 | 59 | false | # 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;
}
}
``` | 2 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | Just Simulating what the questions asks to do | C++| Easy Solution | just-simulating-what-the-questions-asks-0ke87 | IntuitionApproach
Store the location of each number in the matrix in terms of its row index and column index (can use any data structure for this eg map, array) | Lakshit_B | NORMAL | 2025-01-20T17:49:48.644982+00:00 | 2025-01-20T17:49:48.644982+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
1. Store the location of each number in the matrix in terms of its row index and column index (can use any data structure for this eg map, array)
2. Follow the directions array and increment that row and column where the num is present
3. Check if any row is full or any column is full, just return the minumum index
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(m*n) + O(m*n) => O(m*n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(m*n + 1) + O(m) + O(n) => O(m*n)
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int rows = mat.size();
int col = mat[0].size();
vector<pair<int,int>>loc(rows*col+1); //location of each number in the matrix
//population the location of each number
for(int i = 0; i<rows; i++){
for(int j = 0; j<col; j++){
int num = mat[i][j];
loc[num] = {i,j};
}
}
vector<int>r(rows, 0);//array of each row eg-> 0th row, 1st row, 2nd row etc
vector<int>c(col, 0);//array of each column eg->0th col, 1st col, 2nd col etc
int ans = 0;
for(int i = 0; i<arr.size(); i++){
int num = arr[i]; //access the number
int rowIndex = loc[num].first; // find its row from loc array
int colIndex = loc[num].second;//find its col form loc arrya
r[rowIndex]++; //increment the size of that row where this num is present
c[colIndex]++; //similarly increment that column
if(r[rowIndex] == col || c[colIndex] == rows){// now check if any row is full or any column is full just store that index in variable
//(row size = number of colums and column size = number of rows)
ans = i;
break;
}
}
//return ans
return ans;
}
};
``` | 2 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | Easy C++ Solution | easy-c-solution-by-kartikrameshchavan200-edi7 | Code | kartikrameshchavan2003 | NORMAL | 2025-01-20T16:49:15.878094+00:00 | 2025-01-20T16:49:15.878094+00:00 | 57 | false | # Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
map<int, int> mp;
for (int i = 0; i < arr.size(); i++) {
mp[arr[i]] = i;
}
int miniR = INT_MAX;
for (int i = 0; i < n; i++) {
int maxiR = INT_MIN;
for (int j = 0; j < m; j++) {
int ele = mat[i][j];
int ind = mp[ele];
maxiR = max(maxiR, ind);
}
miniR = min(miniR, maxiR);
}
int miniC = INT_MAX;
for (int j = 0; j < m; j++) {
int maxiC = INT_MIN;
for (int i = 0; i < n; i++) {
int ele = mat[i][j];
int ind = mp[ele];
maxiC = max(maxiC, ind);
}
miniC = min(miniC, maxiC);
}
return min(miniR, miniC);
}
};
``` | 2 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | Easy Beginner Friendly C++ Sol | easy-beginner-friendly-c-sol-by-aditya13-u5sm | Please Upvote!!🥺🙏❤️Complexity
Time complexity:O(M∗N)
Space complexity:O((M∗N)+(M+N))=O(M∗N)
Code | aditya13451 | NORMAL | 2025-01-20T16:45:48.753503+00:00 | 2025-01-20T16:45:48.753503+00:00 | 39 | false | # Please Upvote!!🥺🙏❤️
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:$$O(M*N)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O((M*N) + (M+N)) = O(M*N)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int rows = mat.size();
int cols = mat[0].size();
unordered_map<int, pair<int, int>> ump; // val, row, col
vector<int> row_cnt(rows);
vector<int> col_cnt(cols);
for(int r=0; r<rows; r++){
for(int c=0; c<cols; c++){
int val = mat[r][c];
ump[val] = {r, c};
}
}
for(int i=0; i<arr.size(); i++){
int num = arr[i];
auto [r, c] = ump[num];
row_cnt[r]++;
col_cnt[c]++;
if(row_cnt[r] == cols || col_cnt[c] == rows){
return i;
}
}
return -1;
}
};
``` | 2 | 0 | ['Array', 'Hash Table', 'Math', 'Brainteaser', 'Matrix', 'Simulation', 'C++'] | 0 |
first-completely-painted-row-or-column | "Matrix Painting Completion" || Beats 99.09% Users . | matrix-painting-completion-beats-9909-us-u5fx | IntuitionThe problem can be approached by tracking the count of painted cells in each row and column. When either a row or a column becomes fully painted, we re | Yash-8055 | NORMAL | 2025-01-20T14:21:01.711913+00:00 | 2025-01-20T14:21:01.711913+00:00 | 29 | false | 
# Intuition
The problem can be approached by tracking the count of painted cells in each row and column. When either a row or a column becomes fully painted, we return the corresponding index from `arr`.
# Approach
1. Map each number in `mat` to its position (row and column) using a vector for efficient lookup.
2. Maintain two arrays:
- `rowCount` to track the number of painted cells in each row.
- `colCount` to track the number of painted cells in each column.
3. Iterate through `arr` and for each number:
- Locate its position in `mat` using the precomputed mapping.
- Increment the corresponding row and column counts.
- Check if the current row or column is fully painted.
4. Return the index where a row or column is fully painted.
# Complexity
- **Time complexity**:
$$O(m \times n)$$ for preprocessing the mapping and iterating through `arr`.
- **Space complexity**:
$$O(m + n)$$ for `rowCount` and `colCount` arrays.
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
// Map each number in mat to its position
vector<pair<int, int>> pos(m * n + 1); // Using 1-based indexing
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
pos[mat[i][j]] = {i, j};
}
}
// Arrays to track painted cells in rows and columns
vector<int> rowCount(m, 0), colCount(n, 0);
// Iterate through arr and update row/column counts
for (int i = 0; i < arr.size(); ++i) {
auto [r, c] = pos[arr[i]];
if (++rowCount[r] == n || ++colCount[c] == m) {
return i; // Return the first index completing a row or column
}
}
return -1; // Should never be reached
}
};
``` | 2 | 0 | ['Hash Table', 'Matrix', 'Simulation', 'C++'] | 0 |
first-completely-painted-row-or-column | EASY SOLUTION O(M*N) | easy-solution-omn-by-shyam4kb-o08f | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | shyam4KB | NORMAL | 2025-01-20T14:10:44.196757+00:00 | 2025-01-20T14:10:44.196757+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Pair{
int i,j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length, n = mat[0].length;
List<HashSet<Integer>> rowSets = new ArrayList<>();
for (int i =0; i < m; i++) rowSets.add(new HashSet<>());
List<HashSet<Integer>> colSets = new ArrayList<>();
for (int i = 0; i < n; i++) colSets.add(new HashSet<>());
Pair[] table = new Pair[m*n+1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
table[mat[i][j]] = new Pair(i, j);
}
}
for (int i = 0; i < arr.length; i++) {
int r = table[arr[i]].i;
int c = table[arr[i]].j;
HashSet<Integer> set1 = rowSets.get(r);
set1.add(arr[i]);
if (set1.size() == n) return i;
HashSet<Integer> set2 = colSets.get(c);
set2.add(arr[i]);
if (set2.size() == m) return i;
rowSets.set(r, set1);
colSets.set(c, set2);
}
return -1;
}
}
``` | 2 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | Simple Java Code✅|| Simple Approach🔥|| Well Explained🚀 | simple-java-code-simple-approach-well-ex-77dy | IntuitionTo find the smallest index i in arr such that a row or column in mat is completely painted:
Every integer in arr maps uniquely to a cell in mat. This a | ghumeabhi04 | NORMAL | 2025-01-20T13:44:55.973604+00:00 | 2025-01-20T13:44:55.973604+00:00 | 20 | false | # Intuition
To find the smallest index i in arr such that a row or column in mat is completely painted:
1. Every integer in arr maps uniquely to a cell in mat. This allows us to track the painting process.
2. A row is fully painted when all its cells are painted, and similarly for a column.
3. Use counters for rows and columns to keep track of the number of painted cells for each.
---
# Approach
1. Mapping Elements to Coordinates:
- Create a mapping from the value of each cell in mat to its corresponding [row,column] coordinates using a HashMap.
2. Painting Process:
- Traverse through arr, and for each element:
- Retrieve its corresponding [row,column] coordinates using the map.
- Increment the counters for that row and column.
- Check if the row or column is completely painted:
- A row is complete if the counter for that row equals the number of columns.
- A column is complete if the counter for that column equals the number of rows.
3. Return the Result:
- The first index i in arr where either a row or column is completely painted is the result.
---
# Complexity
- Time complexity: O(m⋅n)
- Space complexity: O(m⋅n)
---
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
Map<Integer, int[]> map = new HashMap<>();
int rows = mat.length;
int cols = mat[0].length;
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
int[] array = new int[2];
array[0] = i;
array[1] = j;
map.put(mat[i][j], array);
}
}
int[] r = new int[rows];
int[] c = new int[cols];
for(int i=0; i<arr.length; i++) {
int[] a = map.get(arr[i]);
r[a[0]]++;
c[a[1]]++;
if (r[a[0]] == cols || c[a[1]] == rows) {
return i;
}
}
return 0;
}
}
``` | 2 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | Java Solution | java-solution-by-viper_01-f0es | IntuitionApproachComplexity
Time complexity: O(m∗n)
Space complexity: O(m∗n)
Code | viper_01 | NORMAL | 2025-01-20T13:25:38.378099+00:00 | 2025-01-20T13:25:38.378099+00:00 | 11 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(m*n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(m*n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length, n = mat[0].length;
int row[] = new int[m];
int col[] = new int[n];
Pair[] index = new Pair[m * n + 1];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
index[mat[i][j]] = new Pair(i, j);
}
}
for(int i = 0; i < m * n; i++) {
Pair p = index[arr[i]];
row[p.x]++;
col[p.y]++;
if(row[p.x] == n || col[p.y] == m) {
return i;
}
}
return 0;
}
}
``` | 2 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 1 |
first-completely-painted-row-or-column | Simple Java Solution - Using Brute Force (Beats 80.60%) | simple-java-solution-using-brute-force-b-hj2q | Complexity
Time complexity:
O(m∗n), where m = mat.length & n = mat[0].length
Code | ruch21 | NORMAL | 2025-01-20T12:41:48.582440+00:00 | 2025-01-20T12:41:48.582440+00:00 | 10 | false | # Complexity
- Time complexity:
$$O(m * n)$$, where m = mat.length & n = mat[0].length
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[] rows = new int[m];
int[] cols = new int[n];
HashMap<Integer, int[]> map = new HashMap<>();
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
int[] rowCol = new int[2];
rowCol[0] = i;
rowCol[1] = j;
map.put(mat[i][j], rowCol);
}
rows[i] = n;
}
for(int i=0; i<n; i++) {
cols[i] = m;
}
for(int i=0; i<arr.length; i++) {
int[] rowCol = map.get(arr[i]);
rows[rowCol[0]]--;
cols[rowCol[1]]--;
if(rows[rowCol[0]] == 0 || cols[rowCol[1]] == 0) {
return i;
}
}
return arr.length-1;
}
}
``` | 2 | 0 | ['Java'] | 1 |
first-completely-painted-row-or-column | Easy C++ solution✅ | Beginner friendly💯 | easy-c-solution-beginner-friendly-by-pro-izts | CodeComplexity
Time complexity: O(N*M)
Space complexity: O(N*M) | procrastinator_op | NORMAL | 2025-01-20T11:24:17.853026+00:00 | 2025-01-20T11:24:17.853026+00:00 | 15 | false |
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
map<int, int> cnt_row, cnt_col;
map<int, pair<int, int>> location;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
location[mat[i][j]] = {i, j};
}
}
for(int i=0; i<m*n; i++){
cnt_row[location[arr[i]].first]++;
if(cnt_row[location[arr[i]].first] == n) return i;
cnt_col[location[arr[i]].second]++;
if(cnt_col[location[arr[i]].second] == m) return i;
}
return -1;
}
};
```
# Complexity
- Time complexity: O(N*M)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N*M)
<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 2 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | "Simple" ahh Solution | Beats 100%. | simple-ahh-solution-beats-100-by-anaghab-9aqf | IntuitionApproach
Create a hashmap to store the positions of elements in the matrix.
Traverse the matrix and map each element to its row and column indices.
Ini | AnaghaBharadwaj | NORMAL | 2025-01-20T09:48:23.484322+00:00 | 2025-01-20T09:48:23.484322+00:00 | 28 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
1. Create a hashmap to store the positions of elements in the matrix.
2. Traverse the matrix and map each element to its row and column indices.
3. Initialize arrays to track painted counts for rows and columns.
4. Iterate through the array arr to simulate painting:
- Get the position of the current element from the hashmap.
- Increment the painted count for the corresponding row and column.
- Check if the row or column is completely painted.
- Return the current index if a row or column is fully painted.
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(n * m)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(m)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
HashMap<Integer, int[]>map = new HashMap<>();
int rowcount = mat.length;
int colcount = mat[0].length;
for(int i=0;i<rowcount;++i){
for(int j=0;j<colcount;++j){
map.put(mat[i][j] , new int[]{i,j});
}
}
int rowpaint[] = new int[rowcount];
int colpaint[] = new int[colcount];
for(int i=0;i<arr.length;++i){
int pos[] = map.get(arr[i]);
rowpaint[pos[0]]++;
colpaint[pos[1]]++;
if(rowpaint[pos[0]]==colcount || colpaint[pos[1]]==rowcount){
return i;
}
}
return 0;
}
}
``` | 2 | 0 | ['Java'] | 1 |
first-completely-painted-row-or-column | Easy Solution Ever | easy-solution-ever-by-darshanvala-tmmc | IntuitionThe problem involves finding the first complete index in an array arr when iterating through the elements sequentially and filling rows or columns of a | DarshanVala | NORMAL | 2025-01-20T09:33:12.539566+00:00 | 2025-01-20T09:33:12.539566+00:00 | 14 | false | # Intuition
The problem involves finding the first complete index in an array arr when iterating through the elements sequentially and filling rows or columns of a matrix mat. A row or column is considered complete if all its elements have been encountered in arr at least once.
The approach is to map the positions of matrix elements for quick lookup and track the progress of rows and columns as elements from arr are encountered.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
(1) Input Representation:
mat is a 2D matrix where each element is distinct.
arr is a sequence of integers representing the order in which elements are "filled."
(2) Mapping Matrix Elements:
To quickly locate the row and column of any element in mat, we create two mapping arrays:
rowIndex: Maps each element in mat to its row index.
colIndex: Maps each element in mat to its column index.
Iterate over the matrix mat, and for each element, store its row and column indices in rowIndex and colIndex.
(3) Tracking Progress:
Use two arrays, rowArray and colArray, to track the count of elements encountered for each row and column, respectively.
rowArray[i] indicates how many elements of row i have been filled.
colArray[j] indicates how many elements of column j have been filled.
(4) Processing the Array arr:
Traverse through the array arr. For each element:
Retrieve its row and column indices using rowIndex and colIndex.
Increment the counters for its corresponding row (rowArray) and column (colArray).
(6) After updating the counters:
Check if the current row or column has become "complete" (i.e., its count equals the total number of columns or rows in mat).
If a row or column is complete, return the current index from arr (indicating the first time a row or column becomes fully filled).
(7) Return Value:
If no row or column becomes complete during the traversal of arr, return 0 (though the problem guarantees that there will always be a valid solution).
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
- Mapping Matrix Elements:
𝑂(𝑚 × 𝑛)
O(m × n), where 𝑚 is the number of rows and n is the number of columns in mat.
Processing Array arr: 𝑂(𝑘)
O(k), where k is the length of arr.
Overall: 𝑂(𝑚 × 𝑛 + 𝑘)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
- O(m × n + m + n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int[] rowArray = new int[mat.length];
int[] colArray = new int[mat[0].length];
int[] rowIndex = new int[mat.length * mat[0].length];
int[] colIndex = new int[rowIndex.length];
for(int i=0; i<mat.length; i++){
for(int j=0; j<mat[0].length; j++){
int target = mat[i][j];
rowIndex[target - 1] = i;
colIndex[target - 1] = j;
}
}
for(int i=0; i<arr.length; i++){
int target = arr[i];
// for checking row count
rowArray[rowIndex[target-1]]++;
if(rowArray[rowIndex[target-1]] == mat[0].length){
return i;
}
colArray[colIndex[target-1]]++;
if(colArray[colIndex[target-1]] == mat.length){
return i;
}
}
return 0;
}
}
``` | 2 | 0 | ['Java'] | 0 |
first-completely-painted-row-or-column | 🚀 "Crack the Code: First Completely Painted Row or Column!" 🚀 | crack-the-code-first-completely-painted-lkvfw | אִינטוּאִיצִיָהכאשר פותרים בעיה זו, הרעיון המרכזי הוא לעקוב אחר התקדמות הצביעה של כל שורה ועמודה בזמן אמת. על ידי שמירה על מונים, נוכל לקבוע ביעילות מתי שורה או | HIndaCode | NORMAL | 2025-01-20T08:57:57.112031+00:00 | 2025-01-20T08:57:57.112031+00:00 | 29 | false |
# Intuition
When solving this problem, the key idea is to track the painting progress of each row and column in real time. By maintaining counters, we can efficiently determine when a row or column is fully painted.
# Approach
1. **Mapping Numbers to Positions**:
- First, map each number in the matrix to its position (row, column). This allows quick lookups for any number in the array.
2. **Tracking Progress**:
- Use two counters: one for rows and one for columns. Increment the corresponding counter whenever a number is "painted."
3. **Checking Completion**:
- After updating the counters, check if the current row or column has been fully painted. If yes, return the index of the current number from the array.
4. **Edge Case**:
- If no row or column is completely painted (highly unlikely due to constraints), return `-1`.
# Complexity
- **Time Complexity**:
$$O(m \times n + k)$$, where \(m\) and \(n\) are the dimensions of the matrix, and \(k\) is the length of the array.
- \(O(m \times n)\) for mapping matrix numbers to positions.
- \(O(k)\) for processing the array.
- **Space Complexity**:
$$O(m + n)$$, for the row and column counters.
# Code
```python
class Solution(object):
def firstCompleteIndex(self, arr, mat):
"""
:type arr: List[int]
:type mat: List[List[int]]
:rtype: int
"""
num_to_pos = {}
for i in range(len(mat)):
for j in range(len(mat[0])):
num_to_pos[mat[i][j]] = (i, j)
row_count = [0] * len(mat)
col_count = [0] * len(mat[0])
for index, num in enumerate(arr):
row, col = num_to_pos[num]
row_count[row] += 1
col_count[col] += 1
if row_count[row] == len(mat[0]) or col_count[col] == len(mat):
return index
return -1
```
# 🔥 Why This Stands Out
- **Efficiency**: Combines preprocessing and real-time checks for optimal performance.
- **Simplicity**: Clear logic with minimal data structures.
- **Scalability**: Handles larger matrices and arrays effortlessly.
| 2 | 0 | ['Python'] | 1 |
first-completely-painted-row-or-column | Concise Explanation of Editorial 🤖 | concise-explanation-of-editorial-by-jagg-4xe7 | Brute Force Approach
Map the values in the matrix to their coordinates using a hash map.
Iterate through the array arr, marking the corresponding cell in the ma | _Jatin_Mehra | NORMAL | 2025-01-20T06:46:05.521477+00:00 | 2025-01-20T06:46:05.521477+00:00 | 8 | false | ### Brute Force Approach
1. Map the values in the matrix to their coordinates using a hash map.
2. Iterate through the array `arr`, marking the corresponding cell in the matrix as "visited" (by multiplying it by `-1`).
3. After each update, check if the corresponding row or column is fully visited using helper functions `checkRows` and `checkCols`.
4. If a fully visited row or column is found, return the index of the element in `arr` that caused this.
---
### Optimized Approach (Better Time Complexity)
1. Use a hash map to store the mapping of values in the matrix to their coordinates.
2. Maintain two vectors, `rowCount` and `colCount`, to track the count of visited cells for each row and column.
3. For each element in `arr`, update the count for the corresponding row and column.
4. If the count of any row or column matches its respective size, return the index.
---
### Optimized Approach (Better Space Complexity)
1. Use a hash map to store the index of each value in `arr`.
2. Iterate through each row and column of the matrix, finding the maximum index of the values in `arr` that are part of the current row or column.
3. Track the minimum of these maximum indices to identify the first fully visited row or column.
4. Return the smallest such index.
---
## Complexity Analysis
| **Approach** | **Time Complexity** | **Space Complexity** |
|---------------------------|--------------------------------------|-----------------------------|
| **Brute Force** | \(O(n.m + k.(n + m))\) | \(O(n.m)\) |
| **Optimized (Better TC)** | \(O(n.m + k)\) | \(O(n.m + n + m)\) |
| **Optimized (Better SC)** | \(O(k + n.m)\) | \(O(k)\) |
- \(n\): Number of rows in the matrix.
- \(m\): Number of columns in the matrix.
- \(k\): Size of the array `arr`.
---
# Code
```cpp [Brute]
class Solution {
private:
bool checkRows(int row,vector<vector<int>>& mat){
for(int col = 0;col<mat[0].size();col++){
if(mat[row][col] > 0){
return false;
}
}
return true;
}
bool checkCols(int col,vector<vector<int>>& mat){
for(int row = 0;row<mat.size();row++){
if(mat[row][col] > 0){
return false;
}
}
return true;
}
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int nCols = mat[0].size();
int nRows = mat.size();
unordered_map<int,pair<int,int>>freq;
vector<int>rowCount(nRows,0),colCount(nCols,0);
for(int i=0;i<nRows;i++){
for(int j=0;j<nCols;j++){
int num = mat[i][j];
freq[num] = {i,j};
}
}
for(int i=0;i<arr.size();i++){
int val = arr[i];
auto [row,col] = freq[val];
mat[row][col] = mat[row][col] * -1;
if(checkRows(row,mat) || checkCols(col,mat)){
return i;
}
}
return -1;
}
};
```
```cpp [Better(TC)]
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int nCols = mat[0].size();
int nRows = mat.size();
unordered_map<int,pair<int,int>>freq;
vector<int>rowCount(nRows,0),colCount(nCols,0);
for(int i=0;i<nRows;i++){
for(int j=0;j<nCols;j++){
int num = mat[i][j];
freq[num] = {i,j};
}
}
for(int i=0;i<arr.size();i++){
int val = arr[i];
auto [row,col] = freq[val];
rowCount[row]++, colCount[col]++;
if(rowCount[row]==nCols || colCount[col]==nRows){
return i;
}
}
return -1;
}
};
```
```cpp [Better(SC)]
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int nCols = mat[0].size();
int nRows = mat.size();
unordered_map<int,int>freq;
for(int i=0;i<arr.size();i++){
freq[arr[i]] = i;
}
int minIdx = INT_MAX;
// Rows
for(int row=0;row<nRows;row++){
int maxIdx = INT_MIN;
for(int col=0;col<nCols;col++){
int val = mat[row][col];
int Idx_to_Check = freq[val];
maxIdx = max(maxIdx,Idx_to_Check);
}
minIdx = min(maxIdx,minIdx);
}
//Column
for(int col=0;col<nCols;col++){
int maxIdx = INT_MIN;
for(int row=0;row<nRows;row++){
int val = mat[row][col];
int Idx_to_Check = freq[val];
maxIdx = max(maxIdx,Idx_to_Check);
}
minIdx = min(maxIdx,minIdx);
}
return minIdx;
}
};
``` | 2 | 0 | ['Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Different from other solutions maybe.. ? | different-from-other-solutions-maybe-by-xdp5p | I did not understand the other solutions so I don't know if this is the same thingIntuitionWe first map the elements in the of arr with their respective indexAf | HandleIsConstant | NORMAL | 2025-01-20T06:45:06.381344+00:00 | 2025-01-20T06:45:06.381344+00:00 | 59 | false | I did not understand the other solutions so I don't know if this is the same thing
# Intuition
We first map the elements in the of arr with their respective index
After that we traverse through the matrix row-wise and column-wise
We keep track of which element is coming in the last in the matrix with the help of variable 'temp'
The answer would the element which is coming in the least possible index so we take the minimum there
Doing same for the columns we get the asnwer
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
unordered_map<int, int> mp;
for(int i = 0; i < arr.size(); i++) mp[arr[i]] = i;
int n = mat.size(), m = mat[0].size(), ans = INT_MAX;
for(int i = 0; i < n; i++){
int temp = INT_MIN;
for(int j = 0; j < m; j++){
temp = max(temp, mp[mat[i][j]]);
}
ans = min(temp, ans);
}
for(int i = 0; i < m; i++){
int temp = INT_MIN;
for(int j = 0; j < n; j++){
temp = max(temp, mp[mat[j][i]]);
}
ans = min(temp, ans);
}
return ans;
}
};
``` | 2 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | simple hashmap approach | simple-hashmap-approach-by-wokqsvnwuv-3oz9 | IntuitionApproachIterate the matrix and put in the Hashmap the iterate the array arr and then get the value from the hashmap , making a frequency array to make | woKQsvNWuV | NORMAL | 2025-01-20T06:40:12.886765+00:00 | 2025-01-20T06:40:12.886765+00:00 | 48 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
Iterate the matrix and put in the Hashmap the iterate the array arr and then get the value from the hashmap , making a frequency array to make sure of the count.
# Complexity
- Time complexity:
used O(n*m)
- Space complexity:
Used O(n*m)
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
HashMap<Integer, int[]> mp = new HashMap<>();
int n = mat.length;
int m = mat[0].length;
int nn[] = new int[n];
int mm[] = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mp.put(mat[i][j], new int[] { i, j });
}
}
int tem = 0;
for (int i = 0; i < arr.length; i++) {
int[] value = mp.get(arr[i]);
int f = value[0];
int l = value[1];
nn[f]++;
mm[l]++;
if (nn[f] >= m) {
tem = i;
break;
}
if (mm[l] >=n) {
tem = i;
break;
}
}
return tem;
}
}
``` | 2 | 0 | ['Java'] | 2 |
first-completely-painted-row-or-column | First Completely Painted Row or Column - Easy Explanation - Unique Solution 💯 | first-completely-painted-row-or-column-e-eaxm | Intuition
Finding the maximum latest index at which all the elements in the specific row or column will be painted.
Then find the minimum of the maximum inde | RAJESWARI_P | NORMAL | 2025-01-20T06:08:40.261365+00:00 | 2025-01-20T06:08:40.261365+00:00 | 15 | false | # Intuition
1. Finding the maximum latest index at which all the elements in the specific row or column will be painted.
1. Then find the minimum of the maximum index visited so far so that we can find the smallest index at which specific row or column that can be painted.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
**Initialization**:
Initialize n to be length of the integer array arr.
int n=arr.length;
Initialize map integer array with the size of arr length plus 1 to store the index of the specific array arr.
int[] map=new int[n+1];
Initialize row and col to be the number of rows and columns in the matrix mat.
int row=mat.length;
int col=mat[0].length;
Initialize ans to the Integer.MAX_VALUE to keep track of minimum index at which all elements in the specific row or column is painted.
int ans=Integer.MAX_VALUE;
**Store the index**:
Iterate through all the elements of the integer array arr and store index of each element in the integer array arr in the array map.
for(int i=0;i<n;i++)
{
map[arr[i]]=i;
}
**Iterate through each rows**:
Iterate through all the elements in the matrix mat row-wise.
Outer loop is used to iterate over the row at each iteration, initialize the max to 0 and inner loop is used to iterate over the column.
for(int i=0;i<row;i++){
int max=0;
for(int j=0;j<col;j++){
For each element mat[i][j], retrieve its index from map. This tells us when this element will be painted in the sequence arr and max stores the latest index at which all elements in this row will be painted.
max=Math.max(max,map[mat[i][j]]);
After processing the row, ans is updated to store the minimum max seen so far.
ans=Math.min(ans,max);
**Iterate through each column**:
Iterate through all the elements in the matrix mat column-wise.
Outer loop is used to iterate over the column at each iteration, initialize the max to 0 and inner loop is used to iterate over the row.
for(int i=0;i<col;i++){
int max=0;
for(int j=0;j<row;j++){
For each element mat[j][i], retrieve its index from map. This tells us when this element will be painted in the sequence arr and max stores the latest index at which all elements in this column will be painted.
max=Math.max(max,map[mat[j][i]]);
After processing the row, ans is updated to store the minimum max seen so far.
ans=Math.min(ans,max);
**Returning the value**:
ans represents the smallest index at which either a row or a column in the matrix becomes completely painted.
return ans;
<!-- Describe your approach to solving the problem. -->
# Complexity
- ***Time complexity***: **O(mxn)**.
m -> number of rows in the matrix mat.
n -> number of columns in the matrix mat.
**Mapping**: **O(mxn)**.
Here this loop iterates over all the elements in the array arr which contains **mxn elements**.
**Processing rows and columns**: **O(mxn)**.
**Rows**: **O(mxn)** (each row has n elements, and there are m rows).
**Columns**: **O(mxn)** (each column has m elements, and there are n columns).
**Overall Time Complexity**: **O(mxn)**.
The overall Time Complexity is contributed by Mapping and Processing rows and columns as **O(mxn) + O(mxn) which takes O(mxn) time**.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- ***Space complexity***: **O(mxn)**.
m -> number of rows in the matrix mat.
n -> number of columns in the matrix mat.
**map array**: **O(mxn)**.
map array which stores index of all the elements in the integer array arr whose size is mxn.Hence it takes **O(mxn) space**.
**Other variables**: **O(1)**.
Other variables such as n,row,col,ans,max which takes **constant space**.Hence the space complexity is **O(1)**.
**Overall Space Complexity**: **O(mxn)**.
Overall Space Complexity is contributed by the map integer array.Hence it takes **O(mxn) space in total**.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n=arr.length;
int[] map=new int[n+1];
int row=mat.length;
int col=mat[0].length;
int ans=Integer.MAX_VALUE;
//Store the index of each element in the array arr
for(int i=0;i<n;i++)
{
map[arr[i]]=i;
}
//Iterate through each row columnwise
for(int i=0;i<row;i++)
{
int max=0;
for(int j=0;j<col;j++)
{
//stores latest index at which all the elements in the row will be painted
max=Math.max(max,map[mat[i][j]]);
}
//ans is used to store minimum max seen so far
ans=Math.min(ans,max);
}
for(int i=0;i<col;i++)
{
int max=0;
for(int j=0;j<row;j++)
{
max=Math.max(max,map[mat[j][i]]);
}
ans=Math.min(ans,max);
}
return ans;
}
}
``` | 2 | 0 | ['Array', 'Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | 🔥Beats 95.12%: Array, HashMap (Simple count the row & column) | beats-8994-array-hashmap-simple-count-th-fziz | IntuitionTo determine the first index in arr that completes a row or column in mat, we can map each value in the matrix to its (row, column) position and track | Himanshu1220 | NORMAL | 2025-01-20T05:34:51.437983+00:00 | 2025-01-20T05:37:28.827482+00:00 | 25 | false | 
# **Intuition**
To determine the first index in `arr` that completes a row or column in `mat`, we can map each value in the matrix to its `(row, column)` position and track the count of visited elements in each row and column.
---
# **Approach**
1. **Map Values to Positions:**
- Create a vector `v` such that `v[x] = {row, column}` for each value `x` in the matrix.
2. **Track Counts:**
- Use `row` and `column` vectors to track the number of visited elements in each row and column.
3. **Iterate Through `arr`:**
- For each value in `arr`, increment the count for its row and column.
- If a row or column is fully visited, return the current index.
---
# **Complexity**
- **Time Complexity:** `O(n * m + arr.size())`
- **Space Complexity:** `O(n * m + n + m)`
---
# **Code**
```cpp
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<pair<int, int>> v(n * m + 1);
vector<int> row(n, 0), column(m, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
v[mat[i][j]] = {i, j};
}
}
for (int i = 0; i < arr.size(); i++) {
auto [x, y] = v[arr[i]];
if (++row[x] == m || ++column[y] == n) return i;
}
return -1;
}
};
```
---
# **Example**
### Input:
```cpp
arr = {3, 2, 1, 4, 6, 5};
mat = {
{1, 2, 3},
{4, 5, 6}
};
```
### Output:
```
2
```
| 2 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | C++ solution!!! Easy approach | c-solution-easy-approach-by-yash3002-qnqu | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | YASH3002 | NORMAL | 2025-01-20T05:13:42.173441+00:00 | 2025-01-20T05:13:42.173441+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m=mat.size();
int n=mat[0].size();
vector<int>r(m,0);
vector<int>c(n,0);
unordered_map<int,int>m1,m2;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
m1[mat[i][j]]=i;
m2[mat[i][j]]=j;
}
}
for(int i=0;i<arr.size();i++){
r[m1[arr[i]]]++;
c[m2[arr[i]]]++;
if(r[m1[arr[i]]]==n||c[m2[arr[i]]]==m)return i;
}
return -1;
}
};
``` | 2 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | Easy to understand solution. Beats 100% 😎😎🔥🔥 | easy-to-understand-solution-beats-100-by-4zie | IntuitionFor every row number and column number when a value is encountered increment the count for it's row number and column number. Then check if any of them | nnzl48NW9N | NORMAL | 2025-01-20T04:03:38.222922+00:00 | 2025-01-20T04:03:38.222922+00:00 | 45 | false | # Intuition
For every row number and column number when a value is encountered increment the count for it's row number and column number. Then check if any of them becomes fully colored return that index as smallest value index.
# Approach
1) We need to create mapping for values till m*n so make a vector of size m*n+1 for preparing a mapping of value with it's row and col value.
2) Make 2 vectors rowColorCount and colColorCount to count how many cells of each row and each col has been colored.
3) Iterate the arr and for that value increment the count at it's row and it's col.
4) If any of them becomes full return that index of the iteration.
5) In the end if reached here returing -1 which signifies that getting that smallest index is impossible.
# Complexity
- Time complexity:
O(m*n + arr.size()) = O(m*n)
- Space complexity:
O(m*n + m + n) = O(m*n)
# **Please like the solution if you found it useful🙏🙏🙏🙏**

# Code
```cpp []
typedef pair<int, int> p;
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
// from map make a mapping of the value with it's {row, col}
vector<p> mp(m*n + 1); // coz we need till index m*n
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mp[mat[i][j]] = {i, j};
}
}
vector<int> rowColorCount(m), colColorCount(n);
for(int i = 0; i < arr.size(); i++){
int value = arr[i];
int row = mp[value].first, col = mp[value].second;
if(++rowColorCount[row] == n || ++colColorCount[col] == m) return i;
}
return -1;
}
};
``` | 2 | 0 | ['Ordered Map', 'Matrix', 'Counting', 'Iterator', 'C++'] | 0 |
first-completely-painted-row-or-column | Simple solution Without using HashMap || | simple-solution-without-using-hashmap-by-gc4l | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ritikg4360 | NORMAL | 2025-01-20T03:37:02.102940+00:00 | 2025-01-20T03:37:02.102940+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] pos = new int[m * n + 1][2];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
pos[mat[i][j]] = new int[]{i, j};
}
}
int[] rows = new int[m];
int[] cols = new int[n];
for (int i = 0; i < arr.length; i++) {
int num = arr[i];
int r = pos[num][0];
int c = pos[num][1];
rows[r]++;
cols[c]++;
if (rows[r] == n || cols[c] == m) {
return i;
}
}
return -1;
}
}
``` | 2 | 0 | ['Matrix', 'Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.