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
get-the-maximum-score
DP solution || 100 faster || c++
dp-solution-100-faster-c-by-vvd4-rj79
\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size(),m=nums2.size();\n vector<long long> dp1
vvd4
NORMAL
2021-01-15T11:14:05.020611+00:00
2021-01-15T11:14:05.020648+00:00
162
false
```\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size(),m=nums2.size();\n vector<long long> dp1(n+5,0),dp2(m+5,0);\n int i=0,j=0;\n while(i<n and j<m)\n {\n if(nums1[i]<nums2[j])\n {\n dp1[i+1]=nums1[i]+dp1[i];\n i++;\n }\n else if(nums1[i]>nums2[j])\n {\n dp2[j+1]=dp2[j]+nums2[j];\n j++;\n }\n else {\n dp1[i+1]=dp2[j+1]=max(dp1[i],dp2[j])+nums1[i];\n i++;\n j++;\n }\n }\n while(i<n)\n {\n dp1[i+1]=dp1[i]+nums1[i];\n i++;\n }\n \n while(j<m)\n {\n dp2[j+1]=dp2[j]+nums2[j];\n j++;\n }\n \n return max(dp1[n],dp2[m])%1000000007;\n }\n};\n```
1
0
[]
0
get-the-maximum-score
C++ 2 pointer
c-2-pointer-by-sanzenin_aria-z3u2
```\nclass Solution {\npublic:\n int maxSum(vector& nums1, vector& nums2) {\n long long sum = 0;\n int i=0, j=0;\n while(oneStep(nums1,
sanzenin_aria
NORMAL
2020-09-09T21:58:05.226382+00:00
2020-09-09T21:58:05.226438+00:00
165
false
```\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n long long sum = 0;\n int i=0, j=0;\n while(oneStep(nums1, nums2, i, j, sum));\n return sum % (long long)(1e9+7);\n }\n \n bool oneStep(vector<int>& nums1, vector<int>& nums2, int& i, int& j, long long& sum){\n auto sum1 = sum, sum2 = sum;\n while(i<nums1.size() && j<nums2.size()){\n if(nums1[i] == nums2[j]){\n sum = max(sum1, sum2) + nums1[i];\n i++, j++;\n return true;\n }\n else if(nums1[i] < nums2[j]) sum1 += nums1[i++];\n else sum2 += nums2[j++];\n }\n while(i < nums1.size()) sum1 += nums1[i++];\n while(j < nums2.size()) sum2 += nums2[j++];\n sum = max(sum1, sum2);\n return false;\n }\n};
1
0
[]
0
get-the-maximum-score
Clean Java O(n) solution
clean-java-on-solution-by-mavs0603-88ev
I tried dfs with memo first but realized at the end that this can be solved using a simple linear solution. \n\nWe can think that the two arrays are divided by
mavs0603
NORMAL
2020-09-04T00:39:21.306636+00:00
2020-09-04T00:39:21.306679+00:00
169
false
I tried dfs with memo first but realized at the end that this can be solved using a simple linear solution. \n\nWe can think that the two arrays are divided by their common elements (assume 0 and Integer.MAX_VALUE are also in both the arrays). Since we can swap to another array only if we see a common element then we can simply calculate the sum from last common element and choose the max of the two sum.\n\n```\nclass Solution {\n \n private static long MOD = 1_000_000_007;\n \n public int maxSum(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length, i = 0, j = 0;\n long res = 0, sum1 = 0, sum2 = 0;\n while(i < m || j < n){\n int v1 = i == m ? Integer.MAX_VALUE : nums1[i];\n int v2 = j == n ? Integer.MAX_VALUE : nums2[j];\n if(v1 == v2){\n res += Math.max(sum1, sum2);\n i++;\n j++;\n sum1 = sum2 = v1;\n }else if(v1 < v2){\n sum1 += v1;\n i++;\n }else{\n sum2 += v2;\n j++;\n }\n }\n res += Math.max(sum1, sum2);\n return (int)(res % MOD);\n }\n}\n```
1
0
[]
0
get-the-maximum-score
c++ sol and link to video for understanding the logic
c-sol-and-link-to-video-for-understandin-gkvu
link to nice video solution - https://youtu.be/JkodBYFv24I\n\nclass Solution {\npublic:\n int maxSum(vector<int>& v1, vector<int>& v2) {\n long long i
sahlot01
NORMAL
2020-08-19T18:13:05.819106+00:00
2020-08-19T18:13:05.819153+00:00
183
false
link to nice video solution - https://youtu.be/JkodBYFv24I\n```\nclass Solution {\npublic:\n int maxSum(vector<int>& v1, vector<int>& v2) {\n long long int sum1=0,sum2=0;\n long long int ans=0;\n int x=0; int y=0;\n while(x<v1.size() and y<v2.size()){\n while((x<v1.size() and y<v2.size()) and v1[x]!=v2[y]){\n if(v1[x]<v2[y]){\n sum1+=v1[x];\n x++;\n }else{\n sum2+=v2[y];\n y++;\n }\n }\n if(x==v1.size() || y==v2.size()) break;\n ans+=max(sum1,sum2)+v1[x];\n sum1=0; sum2=0;\n x++; y++;\n }\n while(x<v1.size()){\n sum1+=v1[x];\n x++;\n }\n while(y<v2.size()){\n sum2+=v2[y];\n y++;\n }\n ans+=max(sum1,sum2);\n ans=ans% 1000000007;\n return ans;\n }\n};\n```\n
1
0
[]
0
get-the-maximum-score
:( last test case fails any help !!!!!!!
last-test-case-fails-any-help-by-lug_0-7iiy
\nclass Solution {\npublic:\n \n \n int mod=1000000007;\n \n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n auto a=nums1,b=nums2;\
lug_0
NORMAL
2020-08-13T09:20:56.806179+00:00
2020-08-13T09:20:56.806213+00:00
119
false
```\nclass Solution {\npublic:\n \n \n int mod=1000000007;\n \n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n auto a=nums1,b=nums2;\n \n int curr1=0,curr2=0,res=0;\n \n int i=0,j=0;\n \n while(i<nums1.size()&&j<nums2.size())\n {\n if(a[i]==b[j])\n {\n res=(res+(a[i]+max(curr1,curr2))%mod)%mod;\n curr1=0;\n curr2=0;\n i++;j++;\n }\n \n else if(a[i]>b[j])\n {\n while(j<b.size()&&a[i]>b[j])\n {\n curr2=(curr2+b[j++])%mod;\n }\n }\n else if(a[i]<b[j])\n {\n while(i<a.size()&&a[i]<b[j])\n {\n curr1=(curr1+a[i++])%mod;\n }\n }\n \n }\n \n while(i<a.size())\n {\n curr1=(curr1+a[i++])%mod;\n }\n \n while(j<b.size())\n {\n curr2=(curr2+b[j++])%mod;\n }\n \n res=(res+(max(curr1,curr2))%mod)%mod;\n return res;\n \n }\n};\n```
1
0
[]
1
get-the-maximum-score
Intuitive Top down DP.
intuitive-top-down-dp-by-kbrajesh176-1flf
\nIDEA\nThink of numbers as graph and each nums1[i] has edge to nums2[i + 1] and nums2[j] where nums1[i] == nums2[j] and vice versa.\n\nNow we need to find max
kbrajesh176
NORMAL
2020-08-11T21:40:36.071518+00:00
2020-08-11T21:40:36.071595+00:00
195
false
```\nIDEA\nThink of numbers as graph and each nums1[i] has edge to nums2[i + 1] and nums2[j] where nums1[i] == nums2[j] and vice versa.\n\nNow we need to find max sum ending at Math.max( nums1[n1 - 1], nums2[n2 - 1])\n\nRecurrence state\nF(i, turn) -> Math.max(F(i - 1, turn) F(j - 1, 1 - turn) + nums[i] // based of turn\nnums = if turn == 0, nums1 else nums2\n\nBase F(i, turn) = 0 if i < 0\n```\n\n```\nclass Solution {\n private static final int MOD = 1000000007;\n private long[][] dp;\n private Map<Integer, Integer> map1;\n private Map<Integer, Integer> map2;\n private int[] nums1;\n private int[] nums2;\n public int maxSum(int[] nums1, int[] nums2) {\n // init\n this.nums1 = nums1;\n this.nums2 = nums2;\n int n1 = nums1.length;\n int n2 = nums2.length;\n int n = Math.max(n1, n2);\n dp = new long[2][n];\n map1 = new HashMap<>();\n map2 = new HashMap<>();\n for(int i = 0; i < n1; i++) {\n map1.put(nums1[i], i);\n }\n for(int i = 0; i < n2; i++) {\n map2.put(nums2[i], i);\n }\n for(long[] d : dp) {\n Arrays.fill(d, -1);\n }\n // get maximum ending on both arrays\n long ans = Math.max(helper(n2 - 1, 1), helper(n1 - 1, 0));\n return (int) (ans % MOD);\n }\n \n private long helper(int idx, int turn) {\n if(idx < 0) {\n return 0;\n }\n if(dp[turn][idx] != -1) {\n return dp[turn][idx];\n }\n //System.out.println(idx + " " + turn);\n Map<Integer, Integer> map;\n int[] first;\n int[] second;\n if(turn == 0) {\n map = map2;\n first = nums1;\n second = nums2;\n } else {\n map = map1;\n first = nums2;\n second = nums1;\n }\n long ans = 0;\n \n ans = Math.max(ans, helper(idx - 1, turn) + first[idx]);\n if(map.containsKey(first[idx])) {\n ans = Math.max(ans, helper(map.get(first[idx]) - 1, 1 - turn) + first[idx]);\n }\n dp[turn][idx] = ans;\n //System.out.println(idx + " end " + turn);\n return ans;\n }\n}\n```
1
0
[]
0
get-the-maximum-score
[Java] O(n) Time, O(1) space beat 100% cpu+memory. Explained.
java-on-time-o1-space-beat-100-cpumemory-6sjr
The idea is same as DP:\n\nthe max sum of the full path = the max sum of elements from the beginning to the next common element + the max sum of remaining subpa
arealgeek
NORMAL
2020-08-05T13:16:36.724808+00:00
2020-08-05T13:19:38.720978+00:00
237
false
The idea is same as DP:\n\n`the max sum of the full path` = `the max sum of elements from the beginning to the next common element` + `the max sum of remaining subpaths`\n\nBecause no matter which path leads to the common element `C`, from `C` we can go ahead following any paths to the end, then just need to choose the max path to `C` first.\n\nIn order to do that we need 2 pointers `i`, `j` and 2 sums `sum1`, `sum2`.\n\nUse `i`, `j` to traverse 2 arrays from left to right and find the common element `C`. While traversing calculate the sum for each array: `sum1` is sum of elements of array `nums1` from the begining to the `C`. The same for `sum2` and `nums2`. We only need 2 sums because from `C1` to the next `C2` there are only 2 direct subpaths on each arrays.\n\nAt the common element `C` we set `sum1` = `sum2` = `the max sum of elements from the beginning to C` cause it doesn\'t matter which path led to `C`\n\n\n```\n public int maxSum(int[] nums1, int[] nums2) {\n long sum1 = 0, sum2 = 0;\n int i = 0, j = 0;\n while (i < nums1.length && j < nums2.length) {\n if (nums1[i] < nums2[j]) {\n sum1 += nums1[i++];\n } else if (nums2[j] < nums1[i]) {\n sum2 += nums2[j++];\n } else {\n sum1 = Math.max(sum1, sum2) + nums1[i];\n sum2 = sum1;\n i++;\n j++;\n }\n }\n\n while (j < nums2.length) sum2 += nums2[j++];\n while (i < nums1.length) sum1 += nums1[i++];\n\n return (int) (Math.max(sum1, sum2) % 1000000007);\n }\n```\n\nComplextiy: O(n)\nSpace Complexity: O(1)
1
0
['Two Pointers', 'Java']
0
get-the-maximum-score
Python O(m + n) by DP [w/ Visualization]
python-om-n-by-dp-w-visualization-by-bri-ziip
Python sol by DP\n\n---\n\nScan from left to rigjt.\nIf two numbers are different, update accumulation to the list who has the smaller number.\nThen the updated
brianchiang_tw
NORMAL
2020-08-04T07:45:32.228667+00:00
2020-08-04T07:47:45.479943+00:00
391
false
Python sol by DP\n\n---\n\nScan from left to rigjt.\nIf two numbers are different, update accumulation to the list who has the smaller number.\nThen the updated list moves to next number.\n\nIf two numbers are the same(i.e., common), update accumulation from the larger branch to both list #1 and list #2.\nThen both two lists move to their next numbers.\n\nKeep doing so until all numbers are visited.\n\nFinally, the maximum accumulation value is the answer.\n\nNote:\nRemember to take the module on return, which is defined by description.\n![image](https://assets.leetcode.com/users/images/79e46a8f-479c-4582-b92e-5703ef4ecc46_1596527071.858294.png)\n\n---\n\n**Demo**\n\n![image](https://assets.leetcode.com/users/images/0f871ed5-814b-4f39-913f-672764c0300a_1596526814.2644095.png)\n\n![image](https://assets.leetcode.com/users/images/03e83db4-a329-4789-ab46-e4794928fb76_1596527221.1831665.png)\n\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n \n size_1, size_2 = len(nums1), len(nums2)\n \n idx_1, idx_2 = 0, 0\n \n cur_acc_1, cur_acc_2 = 0, 0\n \n while idx_1 < size_1 or idx_2 < size_2:\n \n pre_acc_1, pre_acc_2 = cur_acc_1, cur_acc_2\n \n if (idx_1 < size_1 and idx_2 < size_2) and nums1[idx_1] == nums2[idx_2]:\n \n # now we have common number, select the larger branch\n # then update accumulation of list 1 and list 2\n accumulation = max(pre_acc_1, pre_acc_2) + nums1[idx_1] \n cur_acc_1, cur_acc_2 = accumulation, accumulation\n \n idx_1, idx_2 = idx_1 + 1, idx_2 + 1\n \n elif idx_1 < size_1 and ((idx_2 == size_2) or (nums1[idx_1] < nums2[idx_2])):\n \n # list 2 meet the end or list 1 has smaller element\n # update accumulation of list 1\n cur_acc_1 = pre_acc_1 + nums1[idx_1] \n idx_1 += 1\n \n elif idx_2 < size_2 and ((idx_1 == size_1) or (nums2[idx_2] < nums1[idx_1])):\n \n # list 1 meet the end or list 2 has smaller element\n # update accumulation of list 2\n cur_acc_2 = pre_acc_2 + nums2[idx_2] \n idx_2 += 1\n \n \n # remember to module constant before return answer\n return max(cur_acc_1, cur_acc_2) % (10**9 + 7)\n```\n
1
0
['Dynamic Programming', 'Python', 'Python3']
0
get-the-maximum-score
Python - Top Down DP - O(N) Time, O(N) Space
python-top-down-dp-on-time-on-space-by-c-lusj
Recursively choose the maximum between staying on the same track and switching to a different track. Switching to a different track (track ^ 1) is possible only
cool_shark
NORMAL
2020-08-02T21:58:41.397289+00:00
2020-08-02T21:58:41.397342+00:00
78
false
Recursively choose the maximum between staying on the same track and switching to a different track. Switching to a different track (`track ^ 1`) is possible only when the same value exists on a different track (`track ^ 1`).\n\nTime complexity: O(N)\nSpace complexity: O(N)\n```py\n\nfrom sys import setrecursionlimit\nsys.setrecursionlimit(1_000_000)\n\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n # build index map for nums1 and nums2\n index_map = {}\n for i, num in enumerate(nums1):\n index_map[(num, 0)] = i\n for i, num in enumerate(nums2):\n index_map[(num, 1)] = i\n \n @functools.lru_cache(None)\n def helper(idx, track):\n if (track == 0 and idx == len(nums1)) or (track == 1 and idx == len(nums2)):\n return 0\n val = nums1[idx] if track == 0 else nums2[idx]\n res = val + helper(idx + 1, track) # same track\n if (val, track ^ 1) in index_map: # different track\n other_idx = index_map[(val, track ^ 1)]\n res = max(res, val + helper(other_idx + 1, track ^ 1))\n \n return res\n \n return max(helper(0, 0), helper(0, 1)) % (10**9 + 7)\n\n```
1
0
[]
1
get-the-maximum-score
[Python] O(n) 600ms solution: use common numbers of two arrays (Heavily Commented)
python-on-600ms-solution-use-common-numb-xzc1
The basic idea behind this solution is to find the common numbers (and the index) of the two arrays and always pick the larger sum of each interval between comm
april_azure
NORMAL
2020-08-02T14:54:14.143287+00:00
2020-08-02T15:03:27.585257+00:00
96
false
The basic idea behind this solution is to find the common numbers (and the index) of the two arrays and always pick the larger sum of each interval between common number\'s of the two arrays.\n\n```\nclass Solution:\n def maxSum(self, a1: List[int], a2: List[int]) -> int:\n if a1[0] >= a2[-1]: return sum(a1)\n if a2[0] >= a1[-1]: return sum(a2)\n \n # the position of each number in a1 and a2\n a1_d = dict(zip(a1, range(len(a1))))\n a2_d = dict(zip(a2, range(len(a2))))\n \n # the common number in both a1 and a2:\n # e.g. [2,4,5,8,10] and [4,6,8,9]\n # common will be [8, 4]\n common = sorted(set(a1) & set(a2), reverse = True)\n \n # Edge case: if no common elements, return the max sum of a1 or a2\n if not common: \n return max(sum(a1), sum(a2))\n \n # from the last common number, sum that index till the tail\n ret = max( sum(a1[a1_d[common[0]]:]), sum(a2[a2_d[common[0]]:]))\n after = common[0]\n \n # for each interval of two common number, use the bigger sum, adding to the result\n for c in common[1:]:\n ret += max( sum(a1[a1_d[c]:a1_d[after]]), sum(a2[a2_d[c]:a2_d[after]]) )\n after = c\n \n # Finally, from the head to the first common number\n ret += max( sum(a1[:a1_d[after]]), sum(a2[:a2_d[after]]) )\n return ret % (10 ** 9 + 7)\n```
1
0
['Python']
0
get-the-maximum-score
C++ two pointers solution linear time complexity
c-two-pointers-solution-linear-time-comp-yeea
\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int i=0,j=0,n=nums1.size(),m=nums2.size();\n long long int
siwaniagrawal18
NORMAL
2020-08-02T11:24:55.051897+00:00
2020-08-02T11:24:55.051932+00:00
71
false
```\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int i=0,j=0,n=nums1.size(),m=nums2.size();\n long long int n1=0,n2=0,mod=1000000007,ans=0;\n while(i<n || j<m){\n if(i<n && (j==m || nums1[i]<nums2[j]))n1+=nums1[i++];\n else if(j<m && (i==n || nums1[i]>nums2[j]))n2+=nums2[j++];\n else{\n ans+=max(n1,n2)+nums1[i];\n n1=0;n2=0;\n i++;j++;\n }\n }\n return (max(n1,n2)+ans)%mod;\n }\n};\n```
1
0
['C++']
0
get-the-maximum-score
Java Solution
java-solution-by-leonhard_euler-195j
\nclass Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long result = 0, sum1 = 0, sum2 = 0;\n int i = 0, j = 0, m = 1_000_000_007
Leonhard_Euler
NORMAL
2020-08-02T08:53:57.978698+00:00
2020-08-02T08:53:57.978750+00:00
83
false
```\nclass Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long result = 0, sum1 = 0, sum2 = 0;\n int i = 0, j = 0, m = 1_000_000_007;\n while(i < nums1.length || j < nums2.length) {\n if(i == nums1.length)\n sum2 += nums2[j++];\n else if(j == nums2.length)\n sum1 += nums1[i++];\n else if(nums1[i] < nums2[j] )\n sum1 += nums1[i++];\n else if(nums2[j] < nums1[i] )\n sum2 += nums2[j++];\n else{\n result = (result + Math.max(sum1 + nums1[i++], sum2 + nums2[j++]) % m) % m;\n sum1 = 0; sum2 = 0;\n }\n }\n \n return (int) (result + Math.max(sum1, sum2) % m) % m;\n }\n}\n```
1
0
[]
0
get-the-maximum-score
Why must only mod at the end???
why-must-only-mod-at-the-end-by-fiya_noo-g44d
If I comment out those two ans %= mod in the dfs, there will be a long case that cannot pass, why???\n\n\nclass Solution {\n private long mod = (long) (1e9 +
fiya_noodles
NORMAL
2020-08-02T04:32:16.142967+00:00
2020-08-02T04:32:16.143002+00:00
74
false
If I comment out those two `ans %= mod` in the dfs, there will be a long case that cannot pass, why???\n\n```\nclass Solution {\n private long mod = (long) (1e9 + 7);\n private Map<Integer, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();\n public int maxSum(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length;\n for (int i = 0; i < m; i++) {\n map1.put(nums1[i], i);\n }\n \n for (int i = 0; i < n; i++) {\n map2.put(nums2[i], i);\n }\n\n int len = Math.max(m, n);\n long[][] dp = new long[len][2];\n \n return (int) Math.max(dfs(nums1, nums2, 0, 0, dp) % mod, dfs(nums1, nums2, 0, 1, dp) % mod);\n }\n \n private long dfs(int[] a, int[] b, int p, int flag, long[][] dp) {\n if ((flag == 0 && p == a.length) || (flag == 1 && p == b.length)) return 0;\n \n if (dp[p][flag] != 0) return dp[p][flag];\n \n long ans = 0;\n \n if (flag == 0) {\n if (map2.containsKey(a[p])) {\n int index = map2.get(a[p]);\n ans = (a[p] + dfs(a, b, index + 1, 1, dp));\n } \n \n ans = Math.max(ans, a[p] + dfs(a, b, p + 1, flag, dp));\n // ans %= mod;\n } else {\n if (map1.containsKey(b[p])) {\n int index = map1.get(b[p]);\n ans = b[p] + dfs(a, b, index + 1, 0, dp);\n } \n \n ans = Math.max(ans, b[p] + dfs(a, b, p + 1, flag, dp));\n // ans %= mod;\n }\n\t\t\n return dp[p][flag] = ans;\n }\n}\n```
1
0
[]
0
get-the-maximum-score
Python | Sorting + Hashmap | O( (M+N) log (M+N) ) , O(M+N)
python-sorting-hashmap-o-mn-log-mn-omn-b-ubwn
\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n order = [(elem, i, 0) for (i,elem) in enumerate(nums1)] + [(elem, i
underoos16
NORMAL
2020-08-02T04:31:08.578270+00:00
2020-08-02T04:31:08.578314+00:00
88
false
```\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n order = [(elem, i, 0) for (i,elem) in enumerate(nums1)] + [(elem, i, 1) for (i,elem) in enumerate(nums2)]\n order.sort()\n\n sets = [ set(nums1), set(nums2)]\n arrays = [ nums1, nums2]\n\n nums1.append(0)\n nums2.append(0)\n\n res = 0\n\n while order:\n elem, self_id, arr_choice = order.pop()\n \n self_arr = arrays[arr_choice]\n other_arr = arrays[arr_choice^1]\n\n max_value = elem + self_arr[self_id + 1]\n\n if elem in sets[arr_choice^1]:\n _, other_id, _ = order.pop()\n max_value = max(max_value, elem + other_arr[other_id+1])\n\n other_arr[other_id] = max_value\n\n self_arr[self_id] = max_value\n\n res = max(res, max_value)\n\n return res % (10**9 + 7)\n\n```
1
0
[]
0
get-the-maximum-score
[Python3] Greedy O(M+N), O(1)Space
python3-greedy-omn-o1space-by-grandb369-brqk
Get the max value if two pointer are pointing the same element\n\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n mod
grandb369
NORMAL
2020-08-02T04:18:49.430893+00:00
2020-08-02T04:18:49.430925+00:00
53
false
Get the max value if two pointer are pointing the same element\n```\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n mod=10**9+7\n n1=n2=0\n while nums1 and nums2:\n if nums1[-1]==nums2[-1]:\n n1+=nums1.pop()\n n2+=nums2.pop()\n n1=n2=max(n1,n2)\n elif nums1[-1]>nums2[-1]:\n n1+=nums1.pop()\n else:\n n2+=nums2.pop()\n if nums1:\n n1+=sum(nums1)\n if nums2:\n n2+=sum(nums2)\n return max(n1,n2)%mod\n```
1
0
[]
0
get-the-maximum-score
[Python3] range sum with two pointers O(M+N)
python3-range-sum-with-two-pointers-omn-au4ua
Algo\nDefine two pointers i and ii to point to nums1 and nums2 respectively. Then, we move the pointer which points to smaller value and update its range sum. I
ye15
NORMAL
2020-08-02T04:11:31.526495+00:00
2020-08-02T04:11:57.687172+00:00
138
false
Algo\nDefine two pointers `i` and `ii` to point to `nums1` and `nums2` respectively. Then, we move the pointer which points to smaller value and update its range sum. If we encounter common value, we add the larger of the two range sum to `ans` and add the common value to `ans` as well. \n\nAt last, we add the larger of the range sum to `ans` one last time. \n\n`O(M+N)` time | `O(1)` space \n\n```\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n ans = i = ii = s = ss = 0\n while i < len(nums1) and ii < len(nums2): \n #update range sum & move pointer \n if nums1[i] < nums2[ii]: \n s += nums1[i] \n i += 1\n elif nums1[i] > nums2[ii]:\n ss += nums2[ii]\n ii += 1\n #add larger range sum to ans\n #add common value & move pointers\n else: \n ans += max(s, ss) + nums1[i]\n s = ss = 0\n i, ii = i+1, ii+1\n #complete the range sum & update ans \n ans += max(s + sum(nums1[i:]), ss + sum(nums2[ii:])) \n return ans % 1_000_000_007\n```
1
0
['Python3']
0
get-the-maximum-score
Java 2 pointer || Simple approach
java-2-pointer-simple-approach-by-rakesh-pzxx
The logic is pretty simple to find the sub-array sum between two common points of the given arrays and add the maximum of them to the result.\nIn case there are
rakesh_yadav
NORMAL
2020-08-02T04:10:13.356354+00:00
2020-08-02T04:15:43.158734+00:00
109
false
The logic is pretty simple to find the sub-array sum between two common points of the given arrays and add the maximum of them to the result.\nIn case there are two or more consecutive common points, simply add one of the common points to the result.\n```\nclass Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long div=(long)(Math.pow(10,9))+7;\n long ans=rec(nums1,nums2,nums1.length,nums2.length);\n ans=ans%div;\n return (int)(ans);\n }\n long max(long x, long y) \n { \n return (x > y) ? x : y; \n } \n \n \n long rec(int ar1[], int ar2[], int m, int n) \n { \n int i = 0, j = 0; \n\t\tlong result = 0, sum1 = 0, sum2 = 0; \n while (i < m && j < n) \n { \n if (ar1[i] < ar2[j]) \n sum1 += ar1[i++]; \n else if (ar1[i] > ar2[j]) \n sum2 += ar2[j++]; \n\t\t else\n\t\t\t\t{ \n result += max(sum1, sum2); \n\t\t\t sum1 = 0; \n sum2 = 0; \n\t\t\t\twhile (i < m && j < n && ar1[i] == ar2[j]) \n { \n result = result + ar1[i++]; \n j++; \n } \n } \n } \n\t\twhile (i < m) \n sum1 += ar1[i++]; \n while (j < n) \n sum2 += ar2[j++]; \n\t\t result += max(sum1, sum2); \n\t\treturn result; \n } \n}\n```
1
0
[]
0
get-the-maximum-score
C++ O(m + n) top-down dp with memoization
c-om-n-top-down-dp-with-memoization-by-m-wk0k
\nclass Solution {\n unordered_map<int, int> pos1, pos2;\n unordered_map<int, long long> out1, out2; \n long long dfs1(int idx, vector<int>& nums1, vec
mingrui
NORMAL
2020-08-02T04:05:59.399827+00:00
2020-08-02T04:05:59.399880+00:00
122
false
```\nclass Solution {\n unordered_map<int, int> pos1, pos2;\n unordered_map<int, long long> out1, out2; \n long long dfs1(int idx, vector<int>& nums1, vector<int>& nums2) {\n if (idx < 0) {\n return 0;\n }\n if (out1.find(idx) != out1.end()) {\n return out1[idx];\n }\n long long result = dfs1(idx - 1, nums1, nums2) + nums1[idx];\n if (pos2.find(nums1[idx]) != pos2.end()) {\n long long r2 = dfs2(pos2[nums1[idx]] - 1, nums1, nums2) + nums1[idx];\n result = max(result, r2);\n }\n out1[idx] = result;\n return result;\n }\n long long dfs2(int idx, vector<int>& nums1, vector<int>& nums2) {\n if (idx < 0) {\n return 0;\n }\n if (out2.find(idx) != out2.end()) {\n return out2[idx];\n }\n long long result = dfs2(idx - 1, nums1, nums2) + nums2[idx];\n if (pos1.find(nums2[idx]) != pos1.end()) {\n long long r2 = dfs1(pos1[nums2[idx]] - 1, nums1, nums2) + nums2[idx];\n result = max(result, r2);\n }\n out2[idx] = result;\n return result;\n }\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n for (int i = 0; i < nums1.size(); i++) {\n pos1[nums1[i]] = i;\n }\n for (int i = 0; i < nums2.size(); i++) {\n pos2[nums2[i]] = i;\n }\n long long result = max(dfs1(nums1.size() - 1, nums1, nums2), dfs2(nums2.size() - 1, nums1, nums2));\n return result % 1000000007;\n }\n};\n```
1
0
[]
0
get-the-maximum-score
simple linear solution O(1) space
simple-linear-solution-o1-space-by-black-g2w3
\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n long long mod=1e9+7;\n int n=nums2.size();\n int m
blackberry25
NORMAL
2020-08-02T04:04:00.483190+00:00
2020-08-02T04:04:00.483324+00:00
139
false
```\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n long long mod=1e9+7;\n int n=nums2.size();\n int m=nums1.size();\n long long sum1=0,sum2=0;\n long long ans=0;\n int i=0,j=0;\n while(i<m && j<n){\n if(nums1[i]>nums2[j]){\n sum2+=nums2[j++];\n }\n else if(nums1[i]<nums2[j]){\n sum1+=nums1[i++];\n }\n else{\n sum2+=nums2[j++];\n sum1+=nums1[i++];\n ans=(ans+max(sum1,sum2))%mod;\n sum1=0,sum2=0;\n }\n \n }\n while(i<m){\n sum1+=nums1[i++];\n \n }\n while(j<n){\n sum2+=nums2[j++];\n \n }\n ans=(ans+max(sum1,sum2))%mod;\n return ans;\n }\n};\n```
1
0
[]
0
get-the-maximum-score
[Java] dfs+memo
java-dfsmemo-by-66brother-t3u0
\nclass Solution {\n Map<Integer,Integer>map1=new HashMap<>();\n Map<Integer,Integer>map2=new HashMap<>();\n int mod=1000000007;\n long dp[][][];\n
66brother
NORMAL
2020-08-02T04:02:20.847020+00:00
2020-08-02T04:02:20.847078+00:00
255
false
```\nclass Solution {\n Map<Integer,Integer>map1=new HashMap<>();\n Map<Integer,Integer>map2=new HashMap<>();\n int mod=1000000007;\n long dp[][][];\n public int maxSum(int[] A, int[] B) {\n for(int i=0;i<A.length;i++){\n map1.put(A[i],i);\n }\n for(int j=0;j<B.length;j++){\n map2.put(B[j],j);\n }\n \n \n dp=new long[Math.max(A.length,B.length)][2][2];\n for(int i=0;i<dp.length;i++){\n for(int j=0;j<dp[0].length;j++){\n Arrays.fill(dp[i][j],-1);\n }\n }\n\n long res=Math.max(dfs(A,B,0,0,0),dfs(A,B,0,1,0));\n return (int)(res%mod);\n }\n \n public long dfs(int A[],int B[],int index,int state,int used){\n \n if(state==0){\n if(index>=A.length)return 0;\n }else{\n if(index>=B.length)return 0;\n }\n \n long res=0;\n \n if(dp[index][state][used]!=-1)return dp[index][state][used];\n \n if(state==0){\n int cur=A[index];\n if(map2.containsKey(cur)){\n if(used==0){\n res=Math.max(res,cur+dfs(A,B,map2.get(cur),1,1));\n }\n }\n if(used==0)res=Math.max(res,cur+dfs(A,B,index+1,state,0));\n else res=Math.max(res,dfs(A,B,index+1,state,0));\n }else{\n int cur=B[index];\n if(map1.containsKey(cur)){\n if(used==0){\n res=Math.max(res,cur+dfs(A,B,map1.get(cur),0,1));\n }\n }\n if(used==0)res=Math.max(res,cur+dfs(A,B,index+1,state,0));\n else res=Math.max(res,dfs(A,B,index+1,state,0));\n }\n dp[index][state][used]=res;\n return res;\n }\n}\n```
1
0
[]
0
get-the-maximum-score
One liner logic,Two pointer,[C++] O(n+m) Time Complexity and O(1) Space
one-liner-logictwo-pointerc-onm-time-com-vj6g
So the One liner logic for this is that if nums1[i]==nums2[j],then the maximum sum you can get till this indexes i,j are \nmax(Sum1[i-1]+nums1[i],Sum2[j-1]+nums
modi_nitin13
NORMAL
2020-08-02T04:01:34.020741+00:00
2020-08-02T04:07:26.101335+00:00
228
false
So the One liner logic for this is that if nums1[i]==nums2[j],then the maximum sum you can get till this indexes i,j are \nmax(Sum1[i-1]+nums1[i],Sum2[j-1]+nums2[j]),Now you can replace can replace Sum1[i]=Sum2[j]=max(Sum1[i-1]+nums1[i],Sum2[j-1]+nums2[j]).\nWhere Sum1[i] is maximum sum which you can get till index i in array one.\nWhere Sum2[j] is maximum sum which you can get till index j in array two.\n```\nclass Solution {\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size(),m=nums2.size(),i,j;\n long long int l1=0,l2=0;\n i=0,j=0;\n while(i<n && j<m)\n {\n if(nums1[i]<nums2[j])\n {\n l1+=(long long int)nums1[i++];\n }\n else if(nums2[j]<nums1[i])\n {\n l2+=(long long int)nums2[j++];\n }\n else\n {\n l1+=(long long int)nums1[i];\n l2+=(long long int)nums1[i];\n long long int a=l1,b=l2;\n l1=max(a,b);\n l2=max(b,a);\n i++;\n j++;\n }\n }\n while(i<n)\n {\n l1+=nums1[i++];\n }\n while(j<m)\n {\n l2+=nums2[j++];\n }\n return max(l1,l2)%1000000007;\n }\n};\n```\nBe carefull of overflow!!
1
0
[]
1
get-the-maximum-score
Java HashMap O(n + m)
java-hashmap-on-m-by-mayank12559-f1mh
\n/*\n Time Complexity: O(n + m)\n Space Complexity: O(n + m)\n */\n public int maxSum(int[] nums1, int[] nums2) {\n long mod = 10000
mayank12559
NORMAL
2020-08-02T04:01:03.910852+00:00
2020-08-02T04:01:03.910886+00:00
310
false
```\n/*\n Time Complexity: O(n + m)\n Space Complexity: O(n + m)\n */\n public int maxSum(int[] nums1, int[] nums2) {\n long mod = 1000000007;\n Map<Integer, Long> hm1 = new HashMap();\n Map<Integer, Long> hm2 = new HashMap();\n hm1.put(0, 0L);\n long cum = 0;\n long ans = 0;\n for(int i: nums1){\n cum += i;\n hm1.put(i, cum);\n }\n hm2.put(0, 0L);\n cum = 0;\n for(int i: nums2){\n cum += i;\n hm2.put(i, cum);\n }\n int prev = 0;\n for(int i: nums1){\n if(hm2.containsKey(i)){\n ans += Math.max(hm2.get(i) - hm2.get(prev) , hm1.get(i) - hm1.get(prev));\n prev = i;\n }\n }\n ans += Math.max(hm1.get(nums1[nums1.length-1]) - hm1.get(prev), hm2.get(nums2[nums2.length - 1]) - hm2.get(prev));\n return (int)(ans % mod);\n }\n```
1
0
[]
0
get-the-maximum-score
Solution using mixture of DP (Top-Down) and Two Pointers and HashTable
solution-using-mixture-of-dp-top-down-an-ffqq
Approach 1Using 3D Dynamic Programming and Two Pointers.(MEMORY LIMIT EXCEEDED)Intuition Maintain index of every element in both arrays in two different hashmap
PradyumnaPrahas2_2
NORMAL
2025-04-04T06:52:14.953691+00:00
2025-04-04T06:52:14.953691+00:00
4
false
# Approach 1 <!-- Describe your approach to solving the problem. --> #### Using 3D Dynamic Programming and Two Pointers. #### (MEMORY LIMIT EXCEEDED) ## Intuition 1) Maintain index of every element in both arrays in two different hashmaps. 2) Initialize a 3D DP array int[][][] dp=new int[a1.len()][a2.len()][3]. Since u can choose any element from both arrays they become your 2 options and since starting is also a condition it will be you third option. 3) Perform memoization , the options you will be having are -> continue with same array. -> change the array. And take these 2 as 2 options and cache you result for further computations. 4) Return the result obtained at starting position. # Complexity time:- O(N^2) space:- O(2*N^2) # Approach 2 #### Using optimized 1D Dynamic Programming (Accepted) Follow the same steps as previous approach, only difference being breaking one 3d array into 2 1d array. Here we dont need option to get cached because we can consider each array as result of the index for a specific option DP Array 1 is results of index using option 1 DP Array 2 is results of index using option 2 So this soln gets accepted but not as efficient as other approaches. But quite innovative :) # Complexity # Code ```java [] class Solution { // 3D DP APPROACH public int backtrack(int[] nums1,int[] nums2,HashMap<Integer,Integer> indexMap1,HashMap<Integer,Integer> indexMap2,int id1,int id2,int[][][] dp,int option){ if(id1>=nums1.length || id2>=nums2.length){ return 0; } if(dp[id1][id2][option]!=-1) return dp[id1][id2][option]; if(option==0){ return dp[id1][id2][option]=Math.max( backtrack(nums1,nums2,indexMap1,indexMap2,id1,id2,dp,1), backtrack(nums1,nums2,indexMap1,indexMap2,id1,id2,dp,2) ); } if(option==1){ int nextIdx=indexMap2.getOrDefault(nums1[id1],-1); indexMap1.remove(nums1[id1]); int maxVal=backtrack(nums1,nums2,indexMap1,indexMap2,id1+1,id2,dp,1); if(nextIdx!=-1){ indexMap2.remove(nums1[id1]); maxVal=Math.max(maxVal,backtrack(nums1,nums2,indexMap1,indexMap2,id1,nextIdx+1,dp,2)); indexMap2.put(nums1[id1],nextIdx); } indexMap1.put(nums1[id1],id1); return dp[id1][id2][option]=maxVal+nums1[id1]; } else{ int nextIdx=indexMap1.getOrDefault(nums2[id2],-1); indexMap2.remove(nums2[id2]); int maxVal=backtrack(nums1,nums2,indexMap1,indexMap2,id1,id2+1,dp,2); if(nextIdx!=-1){ indexMap1.remove(nums2[id2]); maxVal=Math.max(maxVal,backtrack(nums1,nums2,indexMap1,indexMap2,nextIdx+1,id2,dp,1)); indexMap1.put(nums2[id2],nextIdx); } indexMap2.put(nums2[id2],id2); return dp[id1][id2][option]=maxVal+nums2[id2]; } } public int maxSum(int[] nums1, int[] nums2) { HashMap<Integer,Integer> indexMap1=new HashMap<>(); HashMap<Integer,Integer> indexMap2=new HashMap<>(); for(int i=0;i<nums1.length;i++){ indexMap1.put(nums1[i],i); } for(int i=0;i<nums2.length;i++){ indexMap2.put(nums2[i],i); } int[][][] dp=new int[nums1.length][nums2.length][3]; for(int i=0;i<nums1.length;i++){ for(int j=0;j<nums2.length;j++){ Arrays.fill(dp[i][j],-1); } } int ans=backtrack(nums1,nums2,indexMap1,indexMap2,0,0,dp,0); return ans; } } ``` ```java [] class Solution { // COMPROMISED 1D DP APPROACH public long backtrack(int[] nums1,int[] nums2,HashMap<Integer,Integer> indexMap1,HashMap<Integer,Integer> indexMap2,int id,long[] dp1,long[] dp2,int option){ if(option==1){ if(id>=nums1.length) return 0; if(dp1[id]!=-1) return dp1[id]; int nextIdx=indexMap2.getOrDefault(nums1[id],-1); indexMap1.remove(nums1[id]); long maxVal=backtrack(nums1,nums2,indexMap1,indexMap2,id+1,dp1,dp2,1); if(nextIdx!=-1){ indexMap2.remove(nums1[id]); maxVal=Math.max(maxVal,backtrack(nums1,nums2,indexMap1,indexMap2,nextIdx+1,dp1,dp2,2)); indexMap2.put(nums1[id],nextIdx); } indexMap1.put(nums1[id],id); return dp1[id]=maxVal+nums1[id]; } else{ if(id>=nums2.length) return 0; if(dp2[id]!=-1) return dp2[id]; int nextIdx=indexMap1.getOrDefault(nums2[id],-1); indexMap2.remove(nums2[id]); long maxVal=backtrack(nums1,nums2,indexMap1,indexMap2,id+1,dp1,dp2,2); if(nextIdx!=-1){ indexMap1.remove(nums2[id]); maxVal=Math.max(maxVal,backtrack(nums1,nums2,indexMap1,indexMap2,nextIdx+1,dp1,dp2,1)); indexMap1.put(nums2[id],nextIdx); } indexMap2.put(nums2[id],id); return dp2[id]=maxVal+nums2[id]; } } public int maxSum(int[] nums1, int[] nums2) { HashMap<Integer,Integer> indexMap1=new HashMap<>(); HashMap<Integer,Integer> indexMap2=new HashMap<>(); long[] dp1=new long[nums1.length]; long[] dp2=new long[nums2.length]; Arrays.fill(dp1,-1); Arrays.fill(dp2,-1); for(int i=0;i<nums1.length;i++){ indexMap1.put(nums1[i],i); } for(int i=0;i<nums2.length;i++){ indexMap2.put(nums2[i],i); } long ans=Math.max( backtrack(nums1,nums2,indexMap1,indexMap2,0,dp1,dp2,1), backtrack(nums1,nums2,indexMap1,indexMap2,0,dp1,dp2,2) ); int mod=(int)Math.pow(10,9)+7; return (int)(ans%mod); } } ```
0
0
['Array', 'Hash Table', 'Two Pointers', 'Dynamic Programming', 'Java']
0
get-the-maximum-score
O(n) O(1)
on-o1-by-dineshkumar10-r87f
Code
dineshkumar10
NORMAL
2025-03-11T17:47:18.322208+00:00
2025-03-11T17:47:18.322208+00:00
3
false
# Code ```java [] class Solution { public int maxSum(int[] nums1, int[] nums2) { long currSum = 0, sum1 = 0, sum2 = 0; int i = 0; int j = 0; while(i < nums1.length && j < nums2.length){ if(nums1[i] == nums2[j]) { currSum += Math.max(sum1, sum2) + nums2[j]; sum1 = 0; sum2 = 0; i++; j++; } else if(nums1[i] < nums2[j]){ sum1 += nums1[i++]; } else { sum2 += nums2[j++]; } } while(i < nums1.length){ sum1 += nums1[i++]; } while(j < nums2.length){ sum2 += nums2[j++]; } return (int)((currSum + Math.max(sum1, sum2)) % 1000000007); } } ```
0
0
['Java']
0
get-the-maximum-score
c++ 100%
c-100-by-fareedbaba-zd23
IntuitionThe problem requires us to find the maximum sum path between two sorted arrays, where we can switch paths at common elements. Since both arrays are sor
fareedbaba
NORMAL
2025-02-23T11:00:33.955513+00:00
2025-02-23T11:00:33.955513+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to find the maximum sum path between two sorted arrays, where we can switch paths at common elements. Since both arrays are sorted, a two-pointer approach is an efficient way to traverse and accumulate sums while handling intersections. # Approach <!-- Describe your approach to solving the problem. --> Initialize Pointers & Sums: Use two pointers i and j to traverse nums1 and nums2 respectively. Maintain two sum variables a and b to track sums along each path. Traverse Both Arrays Simultaneously: If nums1[i] < nums2[j], add nums1[i] to a and move i. If nums1[i] > nums2[j], add nums2[j] to b and move j. If nums1[i] == nums2[j] (common element), we must choose the maximum sum path so far and continue from that point. Set both a and b to max(a, b) + nums1[i] Move both pointers. Compute Final Maximum: Since the arrays might have different lengths, we add remaining elements in either list to their respective sums. Return max(a, b) % mod to ensure the result does not exceed integer limits. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Since we traverse both arrays once, the time complexity is O(N + M), where N and M are the sizes of nums1 and nums2. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1), as we use only a few integer variables. # Code ```cpp [] class Solution { public: int maxSum(vector<int>& A, vector<int>& B) { int i = 0, j = 0, n = A.size(), m = B.size(); long a = 0, b = 0, mod = 1e9 + 7; while (i < n || j < m) { if (i < n && (j == m || A[i] < B[j])) { a += A[i++]; } else if (j < m && (i == n || A[i] > B[j])) { b += B[j++]; } else { a = b = max(a, b) + A[i]; i++, j++; } } return max(a, b) % mod; } }; ```
0
0
['C++']
0
get-the-maximum-score
C++ solution using set
c-solution-using-set-by-user5947v-36ll
IntuitionApproachComplexity Time complexity: Space complexity: Code
user5947v
NORMAL
2025-01-26T03:41:15.308054+00:00
2025-01-26T03:41:15.308054+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 ```cpp [] class Solution { int n, m; public: int solve(vector<int>& nums1, vector<int>& nums2) { vector<long long> pref1(n+1, 0), pref2(m+1, 0); pref1[1] = nums1[0]; pref2[1] = nums2[0]; for(int i=2;i<=n;i++) pref1[i] = pref1[i-1]+nums1[i-1]; for(int i=2;i<=m;i++) pref2[i] = pref2[i-1]+nums2[i-1]; unordered_map<int, int> mp1; for(int i=0;i<n;i++) mp1[nums1[i]]=i+1; int prev1 = 0; int prev2 = 0; long long res = 0; for(int i=0;i<m;i++) { if(mp1.find(nums2[i])!=mp1.end()) { long long sum1 = pref1[mp1[nums2[i]]-1] - pref1[prev1]; long long sum2 = pref2[i] - pref2[prev2]; res += max(sum1, sum2); prev1 = mp1[nums2[i]]-1; prev2 = i; } } if(nums1[n-1]!=nums2[m-1]) { long long sum1 = pref1[n]-pref1[prev1]; long long sum2 = pref2[m]-pref2[prev2]; res += max(sum1, sum2); } return res%1000000007; } int maxSum(vector<int>& nums1, vector<int>& nums2) { n = nums1.size(); m = nums2.size(); return solve(nums1, nums2); } }; ```
0
0
['C++']
0
get-the-maximum-score
1537. Get the Maximum Score
1537-get-the-maximum-score-by-g8xd0qpqty-53rd
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-13T06:25:48.553756+00:00
2025-01-13T06:25:48.553756+00:00
4
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 maxSum(vector<int>& nums1, vector<int>& nums2) { const int MOD = 1e9 + 7; int i = 0, j = 0; long long sum1 = 0, sum2 = 0, result = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] == nums2[j]) { result = (result + max(sum1, sum2) + nums1[i]) % MOD; sum1 = sum2 = 0; i++, j++; } else if (nums1[i] < nums2[j]) { sum1 += nums1[i++]; } else { sum2 += nums2[j++]; } } while (i < nums1.size()) sum1 += nums1[i++]; while (j < nums2.size()) sum2 += nums2[j++]; result = (result + max(sum1, sum2)) % MOD; return result; } }; ```
0
0
['C++']
0
get-the-maximum-score
DFS Approach, Finding Common Numbers and changing path
dfs-approach-finding-common-numbers-and-3huql
Code
aashaypawar
NORMAL
2024-12-30T00:03:58.618637+00:00
2024-12-30T00:03:58.618637+00:00
9
false
# Code ```java [] import java.util.*; class Solution { private List<List<Integer>> allPaths = new ArrayList<>(); private List<Integer> p = new ArrayList<>(); int currSum = 0; int ans = Integer.MIN_VALUE; public int maxSum(int[] nums1, int[] nums2) { HashMap<Integer, int[]> commons = findCommons(nums1, nums2); dfs(0, nums1, nums2, commons, 1); dfs(0, nums1, nums2, commons, 2); return ans; } private void dfs(int start, int[] nums1, int[] nums2, HashMap<Integer, int[]> commons, int direction) { if (direction == 1 && start >= nums1.length) { ans = Math.max(ans, currSum); return; } else if (direction == 2 && start >= nums2.length) { ans = Math.max(ans, currSum); return; } if (direction == 1 && commons.containsKey(nums1[start])) { p.add(nums1[start]); currSum += nums1[start]; int[] dir = commons.get(nums1[start]); if (dir[0] + 1 < nums1.length) { dfs(dir[0] + 1, nums1, nums2, commons, 1); } if (dir[1] + 1 < nums2.length) { dfs(dir[1] + 1, nums1, nums2, commons, 2); } currSum -= nums1[start]; p.remove(p.size() - 1); } else if (direction == 2 && commons.containsKey(nums2[start])) { p.add(nums2[start]); currSum += nums2[start]; int[] dir = commons.get(nums2[start]); if (dir[0] + 1 < nums1.length) { dfs(dir[0] + 1, nums1, nums2, commons, 1); } if (dir[1] + 1 < nums2.length) { dfs(dir[1] + 1, nums1, nums2, commons, 2); } currSum -= nums2[start]; p.remove(p.size() - 1); } else { if (direction == 1) { p.add(nums1[start]); currSum += nums1[start]; } else if (direction == 2) { p.add(nums2[start]); currSum += nums2[start]; } dfs(start + 1, nums1, nums2, commons, direction); currSum -= p.get(p.size() - 1); p.remove(p.size() - 1); } } private HashMap<Integer, int[]> findCommons(int[] nums1, int[] nums2) { HashMap<Integer, Integer> nums = new HashMap<>(); for (int i = 0; i < nums1.length; i++) { nums.put(nums1[i], i); } HashMap<Integer, int[]> commons = new HashMap<>(); for (int i = 0; i < nums2.length; i++) { if (nums.containsKey(nums2[i])) { commons.put(nums2[i], new int[]{nums.get(nums2[i]), i}); } } return commons; } } ```
0
0
['Java']
0
get-the-maximum-score
Beats 100% | 1ms | Two pointers
beats-100-1ms-two-pointers-by-royalking1-q0rh
IntuitionThe problem involves merging two arrays by picking the maximum sum path when encountering common elements. This strategy minimizes missing out on poten
Royalking12
NORMAL
2024-12-27T18:10:09.600431+00:00
2024-12-27T18:10:09.600431+00:00
4
false
### Intuition The problem involves merging two arrays by picking the maximum sum path when encountering common elements. This strategy minimizes missing out on potential larger sums. --- ### Approach 1. **Two Pointers:** Use two pointers (`i` and `j`) to traverse through both arrays (`nums1` and `nums2`). 2. **Tracking Sums:** Maintain two cumulative sums (`top` and `bottom`) for elements of `nums1` and `nums2`, respectively. 3. **Handling Common Elements:** - When a common element is encountered (`nums1[i] == nums2[j]`), add the maximum of `top` and `bottom` to the final answer `ans` and reset both sums to 0. - Then add the common element to `ans`. 4. **Processing Remaining Elements:** - Once the end of one array is reached, continue adding the remaining elements of the other array to its respective cumulative sum. 5. **Final Update:** Add the larger of `top` and `bottom` to the final answer `ans`. 6. **Modulo Operation:** Return the result modulo \(10^9 + 7\) as required. --- ### Complexity - **Time Complexity:** \(O(n + m)\) - Each array is traversed once, where \(n\) and \(m\) are the lengths of `nums1` and `nums2`. - **Space Complexity:** \(O(1)\) - Only a few variables are used to keep track of the cumulative sums and pointers. --- ### Suggested Improvements 1. **Edge Cases:** Ensure edge cases like one array being empty or having no common elements are handled explicitly. 2. **Modulo Inside Loop:** Instead of applying the modulo operation at the end, apply it during updates to `ans` to avoid overflow when `nums1` and `nums2` have large elements. --- ### Updated Code ```cpp class Solution { public: int maxSum(vector<int>& nums1, vector<int>& nums2) { const int MOD = 1e9 + 7; long long ans = 0, top = 0, bottom = 0; int i = 0, j = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) { top += nums1[i++]; } else if (nums1[i] > nums2[j]) { bottom += nums2[j++]; } else { ans = (ans + max(top, bottom) + nums1[i]) % MOD; top = bottom = 0; i++; j++; } } while (i < nums1.size()) { top += nums1[i++]; } while (j < nums2.size()) { bottom += nums2[j++]; } ans = (ans + max(top, bottom)) % MOD; return ans; } }; ```
0
0
['C++']
0
get-the-maximum-score
Get Maximum Score - Solution in Java
get-maximum-score-solution-in-java-by-so-u2f2
Approach Two-pointer technique: Traverse both arrays simultaneously using two pointers i1 and i2. Maintain two sums, s1 and s2, to track the cumulative sum of v
sowmy3010
NORMAL
2024-12-26T05:19:39.417625+00:00
2024-12-26T05:19:39.417625+00:00
10
false
# Approach - Two-pointer technique: `Traverse both arrays simultaneously using two pointers i1 and i2.` `Maintain two sums, s1 and s2, to track the cumulative sum of values in nums1 and nums2 until a common value is encountered.` `When a common value is found, add the maximum of s1 and s2 to the result (max) and reset the sums.` - After the traversal: `Add the remaining elements of nums1 and nums2 to their respective sums.` `Add the larger of the two remaining sums to the result.` - Take the result modulo 10^9 + 7 # Complexity - Time complexity: O(M+N) - Space complexity: O(1) # Code ```java [] class Solution { public int maxSum(int[] nums1, int[] nums2) { long s1=0, s2=0; int m=nums1.length; int n=nums2.length; int i1=0, i2=0; long max=0; while(i1!=m && i2!=n){ if(nums1[i1]<nums2[i2]){ s1+=nums1[i1]; i1++; } else if(nums2[i2]<nums1[i1]){ s2+=nums2[i2]; i2++; } else if(nums1[i1]==nums2[i2]){ max += Math.max(s1,s2) + nums1[i1]; s1=0; s2=0; i1++; i2++; } } while(i1!=m){ s1+=nums1[i1]; i1++; } while(i2!=n){ s2+=nums2[i2]; i2++; } max+=Math.max(s1,s2); return ((int)(max%1000000007)); } } ```
0
0
['Java']
0
get-the-maximum-score
C++ two pointer dp solution
c-two-pointer-dp-solution-by-rushibhosle-ncoy
IntuitionApproachComplexity Time complexity: Space complexity: Code
rushibhosle155
NORMAL
2024-12-19T19:38:59.081516+00:00
2024-12-19T19:38:59.081516+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 ```cpp [] class Solution { public: int maxSum(vector<int>& nums1, vector<int>& nums2) { int mod = 1e9+7; int n = max(nums1.size(), nums2.size()); vector<vector<long long int>> dp(n, vector<long long int>(2,0)); int i=0,j=0; int n1 = nums1.size(), n2 = nums2.size(); while(i<n1 || j<n2){ if(j>=n2 || (i<n1 && nums1[i] < nums2[j] )){ dp[i][0] = nums1[i] + (i>0? dp[i-1][0]:0); i++; } else if(i>=n1 || (j<n2 && nums2[j]<nums1[i])){ dp[j][1] = nums2[j] + (j>0? dp[j-1][1]:0); j++; } else if(i<n1 && j<n2 && nums1[i] == nums2[j]){ dp[i][0] = nums1[i] + (i>0? dp[i-1][0]:0); dp[j][1] = nums2[j] + (j>0? dp[j-1][1]:0); dp[i][0] = dp[j][1] = max(dp[i][0], dp[j][1]); i++; j++; } } return max(dp[n1-1][0], dp[n2-1][1]) % mod; } }; ```
0
0
['C++']
0
get-the-maximum-score
MOD SUCKS
mod-sucks-by-vaishnaviishah-4lgz
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
vaishnaviishah
NORMAL
2024-11-15T21:50:56.998587+00:00
2024-11-15T21:50:56.998617+00:00
2
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```cpp []\nclass Solution {\npublic:\n int mod = 1e9+7;\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n long long int i = 0, j = 0, sum1=0, sum2 = 0, ans = 0;\n while(i < nums1.size() && j<nums2.size()){\n if(nums1[i] < nums2[j]){\n sum1 += nums1[i++];\n }else if(nums1[i]> nums2[j]){\n sum2 += nums2[j++];\n }else{\n ans += (max(sum1, sum2));\n ans += nums1[i];\n sum1 = 0; sum2 = 0;\n i++;\n j++;\n }\n }\n while(i<nums1.size()){\n sum1 += nums1[i++];\n }\n while(j<nums2.size()){\n sum2 += nums2[j++];\n }\n return (ans + max(sum1,sum2))%mod;\n }\n};\n```
0
0
['C++']
0
get-the-maximum-score
js dfs solution
js-dfs-solution-by-swu1747-zg9j
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
swu1747
NORMAL
2024-11-14T21:41:45.373310+00:00
2024-11-14T21:41:45.373339+00:00
8
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```javascript []\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxSum = function (nums1, nums2) {\n const n = nums1.length, m = nums2.length, mod = Math.pow(10, 9) + 7\n const hash = {}, hash1 = {}\n for (let i = 0; i < n; i++) {\n hash[nums1[i]] = i\n }\n for (let i = 0; i < m; i++) {\n if (hash[nums2[i]]!==undefined) {\n hash1[nums2[i]] = [hash[nums2[i]], i]\n }\n }\n const memo1 = new Array(n).fill(-1), memo2 = new Array(m).fill(-1)\n const dfs = (cur, x) => {\n if (cur < 0) {\n return 0\n }\n if (!x) {\n if (memo1[cur] !== -1) {\n return memo1[cur]\n }\n if (hash1[nums1[cur]]) {\n memo1[cur] = Math.max(dfs(hash1[nums1[cur]][0] - 1, 0), dfs(hash1[nums1[cur]][1] - 1, 1)) + nums1[cur]\n } else {\n memo1[cur] = dfs(cur - 1, x) + nums1[cur] \n }\n return memo1[cur]\n } else {\n if (memo2[cur] !== -1) {\n return memo2[cur]\n }\n if (hash1[nums2[cur]]) {\n memo2[cur] = Math.max(dfs(hash1[nums2[cur]][0] - 1, 0), dfs(hash1[nums2[cur]][1] - 1, 1)) + nums2[cur]\n } else {\n memo2[cur] = (dfs(cur - 1, x) + nums2[cur])\n }\n return memo2[cur]\n }\n }\n const x = Math.max(dfs(n - 1, false), dfs(m - 1, true))\n return x % mod\n};\n\n```
0
0
['Dynamic Programming', 'Recursion', 'JavaScript']
0
get-the-maximum-score
Python (Simple Two Pointers)
python-simple-two-pointers-by-rnotappl-0m0a
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
rnotappl
NORMAL
2024-11-05T14:59:41.790889+00:00
2024-11-05T14:59:41.790933+00:00
8
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```python3 []\nclass Solution:\n def maxSum(self, nums1, nums2):\n n, m, mod = len(nums1), len(nums2), 10**9+7 \n i, j, total, sum_1, sum_2 = 0, 0, 0, 0, 0 \n\n while i < n and j < m:\n if nums1[i] == nums2[j]:\n total += max(sum_1,sum_2) + nums1[i]\n sum_1 = 0 \n sum_2 = 0 \n i += 1 \n j += 1 \n elif nums1[i] < nums2[j]:\n sum_1 += nums1[i]\n i += 1\n else:\n sum_2 += nums2[j] \n j += 1 \n\n while i < n:\n sum_1 += nums1[i]\n i += 1 \n\n while j < m:\n sum_2 += nums2[j]\n j += 1 \n\n total += max(sum_1,sum_2)\n\n return total%mod \n```
0
0
['Python3']
0
get-the-maximum-score
C++ , Simple , Memoization , Recursion , Simple
c-simple-memoization-recursion-simple-by-80di
Intuition\n\n\n# Approach\n\n# Complexity\n\n# Code\ncpp []\nclass Solution {\n int MOD=1e9+7;\n long long find(int i,bool firstvec,int n,int m,unordered_
harshbondarde
NORMAL
2024-11-05T10:43:04.817454+00:00
2024-11-05T10:43:04.817485+00:00
21
false
# Intuition\n\n\n# Approach\n\n# Complexity\n\n# Code\n```cpp []\nclass Solution {\n int MOD=1e9+7;\n long long find(int i,bool firstvec,int n,int m,unordered_map<int,int>&m1,unordered_map<int,int>&m2,vector<int>&nums1,vector<int>&nums2,vector<vector<long long>>&dp){\n if((firstvec && i>=n) || (!firstvec && i>=m))\n return 0;\n if(dp[i][firstvec]!=-1)\n return dp[i][firstvec];\n long long ans=0;\n if(firstvec){\n ans=max(ans,(nums1[i]+find(i+1,true,n,m,m1,m2,nums1,nums2,dp)));\n if(m1[nums1[i]]!=-1){\n ans=max(ans,(nums1[i]+find(m1[nums1[i]]+1,false,n,m,m1,m2,nums1,nums2,dp)));\n }\n \n }else{\n ans=max(ans,(nums2[i]+find(i+1,false,n,m,m1,m2,nums1,nums2,dp)));\n if(m2[nums2[i]]!=-1){\n ans=max(ans,(nums2[i]+find(m2[nums2[i]]+1,true,n,m,m1,m2,nums1,nums2,dp)));\n }\n }\n return dp[i][firstvec]=ans;\n }\npublic:\n int maxSum(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n int m=nums2.size();\n \n unordered_map<int,int>m1;\n unordered_map<int,int>m2;\n for(int i=0;i<n;i++){\n m1[nums1[i]]=-1;\n }\n for(int j=0;j<m;j++){\n if(m1.count(nums2[j])){\n m1[nums2[j]]=j;\n }\n }\n\n for(int j=0;j<m;j++){\n m2[nums2[j]]=-1;\n }\n for(int i=0;i<n;i++){\n if(m2.count(nums1[i])){\n m2[nums1[i]]=i;\n }\n }\n int size=max(n,m);\n vector<vector<long long>>dp(size+1,vector<long long>(2,-1));\n return max(find(0,true,n,m,m1,m2,nums1,nums2,dp),find(0,false,n,m,m1,m2,nums1,nums2,dp))%MOD;\n }\n};\n```
0
0
['Array', 'Hash Table', 'Two Pointers', 'Dynamic Programming', 'Greedy', 'C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Brute-Force and One-Liner
brute-force-and-one-liner-by-votrubac-1rf5
I am sure some clever solution exists, but I did not want to spend too much time.\n\nYou can realize that the number of strings that match the criteria is very
votrubac
NORMAL
2022-05-28T16:02:26.180746+00:00
2022-05-28T21:18:51.340519+00:00
3,889
false
I am sure some clever solution exists, but I did not want to spend too much time.\n\nYou can realize that the number of strings that match the criteria is very small - 7, to be exact (see the second solution below).\n\n#### Brute-Force\n**C++**\n```cpp\nbool digitCount(string num) {\n int cnt[10] = {};\n for (auto n : num)\n ++cnt[n - \'0\'];\n for (int i = 0; i < num.size(); ++i)\n if (cnt[i] != num[i] - \'0\')\n return false;\n return true;\n}\n```\n\n#### One-Liner\n```cpp\nbool digitCount(string &num) {\n return unordered_set<string>{"1210", "2020" , "21200", "3211000", "42101000", "521001000", "6210001000"}.count(num);\n}\n```
36
0
['C']
12
check-if-number-has-equal-digit-count-and-digit-value
Java || Using Freq Array || Easy Straightforward Solution
java-using-freq-array-easy-straightforwa-hvv9
UpVote if u find this Solution Useful\n\n\nclass Solution {\n public boolean digitCount(String num) {\n int[] freqArr = new int[10]; // n = 10 given
Shadab_mehmood
NORMAL
2022-05-28T16:31:14.512273+00:00
2022-05-28T16:43:19.002742+00:00
3,434
false
***UpVote if u find this Solution Useful***\n\n```\nclass Solution {\n public boolean digitCount(String num) {\n int[] freqArr = new int[10]; // n = 10 given in constraints;\n \n \n for(char ch : num.toCharArray()){\n freqArr[ch-\'0\']++;\n }\n \n for(int i=0;i<num.length();i++){\n int freq = num.charAt(i)-\'0\'; //freq of each indexValue;\n freqArr[i] = freqArr[i] - freq; \n }\n for(int i=0;i<10;i++){\n if(freqArr[i]!=0){\n return false;\n }\n }\n return true;\n }\n}\n```
23
0
['Java']
1
check-if-number-has-equal-digit-count-and-digit-value
[Java/Python 3] Simple code.
javapython-3-simple-code-by-rock-rgee
java\n public boolean digitCount(String num) {\n int[] cnt = new int[11];\n char[] charArr = num.toCharArray();\n for (char d : charArr)
rock
NORMAL
2022-05-28T16:03:07.781379+00:00
2022-05-28T16:23:48.983529+00:00
1,853
false
```java\n public boolean digitCount(String num) {\n int[] cnt = new int[11];\n char[] charArr = num.toCharArray();\n for (char d : charArr) {\n ++cnt[d - \'0\'];\n }\n for (int i = 0; i < charArr.length; ++i) {\n if (cnt[i] != charArr[i] - \'0\') {\n return false;\n }\n }\n return true;\n }\n```\n```python\n def digitCount(self, num: str) -> bool:\n c = Counter(map(int, num))\n return all(c[i] == int(d) for i, d in enumerate(num))\n```
17
1
[]
1
check-if-number-has-equal-digit-count-and-digit-value
Confusing yet simple Hashmap Solution C++
confusing-yet-simple-hashmap-solution-c-esanw
This question was really easy, but head scratching at the same time. I had to waste so much time only because of the confusion to chose number or character type
NeerajSati
NORMAL
2022-05-28T16:01:30.506774+00:00
2022-05-29T07:39:15.625096+00:00
2,615
false
This question was really easy, but head scratching at the same time. I had to waste so much time only because of the confusion to chose number or character type hashmap.\nSo, for simplicity we will maintain a int to int hashmap, which will store the frequency of a particular number.\nThen for every index, **we have to check if the frequency of that index in hashmap is equal to the number at that index**.\nHere is the solution too \uD83D\uDE0A\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int> mpp;\n int n= num.length();\n for(auto it:num){\n int x = it - \'0\';\n mpp[x]++; // Store the frequency of the char as a number\n }\n for(int i=0;i<n;i++){\n int x = num[i] - \'0\'; // get the char as number\n \xA0 \xA0 \xA0 \xA0 \xA0 \xA0if(mpp[i] != x) // f the number is not equal to its frequency we return false\n return false;\n }\n return true;\n }\n};\n\n```\n\n**Approach 2:**\nWe just count the occurences of that index in the string. Thanks to @VisD566 for this approach.\n\n```\nbool digitCount(string s) {\n for(int i=0; i<s.size(); i++){\n if(count(s.begin(), s.end(), i+\'0\') != s[i]-\'0\')\n return false;\n }\n return true;\n}\n```
16
1
['String', 'C']
4
check-if-number-has-equal-digit-count-and-digit-value
Easy Python3 Solution using Count
easy-python3-solution-using-count-by-lal-o3ue
\n# Code\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if int(num[i]) != num.count(str(i)):\n
Lalithkiran
NORMAL
2023-02-09T16:06:05.038245+00:00
2023-02-09T16:06:05.038329+00:00
1,311
false
\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if int(num[i]) != num.count(str(i)):\n return False\n return True\n```
9
0
['Python3']
1
check-if-number-has-equal-digit-count-and-digit-value
✅[C++] || ✅Map solution || ✅O(N) || Easy and clean code
c-map-solution-on-easy-and-clean-code-by-lj5g
\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<char, int> mpp;\n \n for(int i=0; i<num.size(); i++)\n
shm_47
NORMAL
2022-05-28T16:03:53.792491+00:00
2023-06-13T19:22:20.997582+00:00
1,636
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<char, int> mpp;\n \n for(int i=0; i<num.size(); i++)\n mpp[num[i]]++;\n \n\n for(int i=0; i<num.size(); i++){\n char c =\'0\' + i;\n // cout<<c<<endl;\n if(num[i] != \'0\' + mpp[c]){\n // cout<<num[i]<<" "<<mpp[c]<<endl;\n return false;\n }\n \n }\n \n return true;\n }\n};\n```\n\n**Check out my youtube channel for related content\nhttps://www.youtube.com/@ignition548/featured**
9
0
['C']
0
check-if-number-has-equal-digit-count-and-digit-value
📌 [JAVA] | Simple
java-simple-by-kanojiyakaran-9mrb
\nclass Solution {\n public boolean digitCount(String num) {\n \n int indexCount[] = new int[10];\n \n for(char c:num.toCharArr
kanojiyakaran
NORMAL
2022-05-28T16:01:45.103343+00:00
2022-05-29T08:38:29.294322+00:00
1,543
false
```\nclass Solution {\n public boolean digitCount(String num) {\n \n int indexCount[] = new int[10];\n \n for(char c:num.toCharArray()){\n indexCount[c-\'0\']++;\n }\n \n for(int i=0;i<num.length();i++){\n if(Character.getNumericValue(num.charAt(i)) != indexCount[i])\n return false; \n }\n \n return true;\n }\n}\n \n\n```\n
8
0
['Array', 'Java']
2
check-if-number-has-equal-digit-count-and-digit-value
Simple and fast JavaScript/TypeScript solution
simple-and-fast-javascripttypescript-sol-hlxm
My simple and fast JS/TS solution:\n\nfunction digitCount(num: string): boolean {\n const arr = Array(num.length).fill(0);\n for (const char of num) {\n
alexandresheva
NORMAL
2022-06-09T22:04:54.160268+00:00
2022-06-09T22:04:54.160294+00:00
743
false
My simple and fast JS/TS solution:\n```\nfunction digitCount(num: string): boolean {\n const arr = Array(num.length).fill(0);\n for (const char of num) {\n arr[Number(char)]++;\n }\n return arr.join(\'\') === num;\n};\n```\n\nResult:\nRuntime:\xA073 ms, faster than\xA097.44%\xA0of\xA0TypeScript\xA0online submissions for\xA0Check if Number Has Equal Digit Count and Digit Value.\nMemory Usage:\xA044.5 MB, less than\xA053.85%\xA0of\xA0TypeScript\xA0online submissions for\xA0Check if Number Has Equal Digit Count and Digit Value.\n
7
0
['TypeScript', 'JavaScript']
1
check-if-number-has-equal-digit-count-and-digit-value
Straightforward
straightforward-by-shishir_sharma-a2af
\nclass Solution {\npublic:\n bool digitCount(string nums) {\n unordered_map<int,int> umap;\n for(int i=0;i<nums.length();i++)\n {\n
Shishir_Sharma
NORMAL
2022-05-28T16:03:46.801285+00:00
2022-05-28T16:03:46.801316+00:00
1,082
false
```\nclass Solution {\npublic:\n bool digitCount(string nums) {\n unordered_map<int,int> umap;\n for(int i=0;i<nums.length();i++)\n {\n string temp="";\n temp+=nums[i];\n int n=stoi(temp);\n umap[n]++;\n }\n for(int i=0;i<nums.length();i++)\n {\n string temp="";\n temp+=nums[i];\n int n=stoi(temp);\n \n //Number of times expected != Number of times occured \n if(n!=umap[i])\n return false;\n \n }\n return true;\n }\n};\n```\n**Like it? Please Upvote ;-)**
7
0
['C', 'C++']
0
check-if-number-has-equal-digit-count-and-digit-value
[Python 3] Using Counter fast solution + One-Liner
python-3-using-counter-fast-solution-one-gzq6
Approach: Create a dict storing frequency of each number and then just compare the index with frequency.\n\n\nfrom collections import Counter\n\nclass Solution:
codesankalp
NORMAL
2022-05-28T16:08:00.230027+00:00
2022-06-01T16:56:08.131861+00:00
1,169
false
Approach: Create a dict storing frequency of each number and then just compare the index with frequency.\n\n```\nfrom collections import Counter\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n d = Counter(num)\n for i in range(len(num)):\n if int(num[i])!=d.get(str(i), 0):\n return False\n return True\n```\n\nTwo-Liner:\n\n```\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n d = collections.Counter(num)\n return all([int(num[i])==d.get(str(i), 0) for i in range(len(num))])\n```\n\nOne Liner (slight modification):\n\n```\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n return all([int(num[i])==Counter(num)[f\'{i}\'] for i in range(len(num))])\n```
6
0
['Python']
3
check-if-number-has-equal-digit-count-and-digit-value
✨🔥💫Here it's my 9 Languages💯Faster ☠ Easy 🧠W/Explanation with Images Beats 100☠🎉🎊✅✅✅
here-its-my-9-languagesfaster-easy-wexpl-9niy
Intuition\n\n\n\n\n\n\njavascript []\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function (num) {\n const arr = Array(num.lengt
Edwards310
NORMAL
2024-02-27T06:41:30.285026+00:00
2024-05-27T00:47:24.537545+00:00
412
false
# Intuition\n![Screenshot 2024-02-27 110756.png](https://assets.leetcode.com/users/images/3dd3bc19-f6a1-40f3-ad13-e6924d5a38ba_1709013445.3136506.png)\n![Screenshot 2024-02-27 110854.png](https://assets.leetcode.com/users/images/ae67c29e-b033-4ce2-b1c7-65ae07b195d1_1709013451.746271.png)\n![Screenshot 2024-02-27 110941.png](https://assets.leetcode.com/users/images/d7c758d4-ac87-4132-a8a5-b83b8343f514_1709013456.5429547.png)\n![Screenshot 2024-02-27 111021.png](https://assets.leetcode.com/users/images/6d751bbb-3238-4791-80eb-f834739af39b_1709013462.095549.png)\n![Screenshot 2024-02-27 121041.png](https://assets.leetcode.com/users/images/23077522-5665-4c12-ae25-604e8f83594f_1709016065.597602.png)\n\n```javascript []\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function (num) {\n const arr = Array(num.length).fill(0)\n for (let elem of num) {\n arr[elem]++\n }\n return arr.join(\'\') == num\n};\n```\n```C []\nbool digitCount(char* num) {\n int arr[10] = {};\n for (int i = 0; num[i] != \'\\0\'; i++)\n arr[num[i] - \'0\']++;\n for (int i = 0; i < strlen(num); ++i) {\n int x = num[i] - \'0\';\n if (arr[i] == x)\n continue;\n else\n return false;\n }\n return true;\n}\n```\n```python3 []\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if int(num[i]) != num.count(str(i)):\n return False\n return True\n```\n```C++ []\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int, int> mp;\n for (auto& x : num)\n mp[x - \'0\']++;\n for (int i = 0; i < num.length(); ++i) {\n if (mp[i] == num.at(i) - \'0\')\n continue;\n else\n return false;\n }\n return true;\n }\n};\n```\n```Typescript []\nfunction digitCount(num: string): boolean {\n const arr = Array(num.length).fill(0);\n for (const char of num)\n arr[Number(char)]++;\n \n return arr.join(\'\') === num;\n};\n```\n```python []\nclass Solution(object):\n def digitCount(self, num):\n """\n :type num: str\n :rtype: bool\n """\n list = [0] * 10\n for n in num:\n list[int(n)] += 1\n \n for i in range(0, len(num)):\n if list[i] == int(num[i]):\n continue\n else:\n return False\n return True\n\n\n \n```\n```Java []\nclass Solution {\n public boolean digitCount(String num) {\n int[] hash = new int[10];\n for (int i = 0; i < num.length(); i++)\n hash[num.charAt(i) - \'0\']++;\n for (int i = 0; i < num.length(); ++i) {\n if (hash[i] == num.charAt(i) - \'0\')\n continue;\n else\n return false;\n }\n return true;\n }\n}\n```\n``` C# []\npublic class Solution {\n public bool DigitCount(string num) {\n int []arr = new int[10];\n for (int i = 0; i < num.Length; i++)\n arr[num[i] - \'0\']++;\n for (int i = 0; i < num.Length; ++i) {\n if (arr[i] == num[i] - \'0\')\n continue;\n else\n return false;\n }\n return true;\n }\n}\n```\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 O(n) --> n = string length\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(26) --> O(1)\n# Code\n```\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function (num) {\n const arr = Array(num.length).fill(0)\n for (let elem of num) {\n arr[elem]++\n }\n return arr.join(\'\') == num\n};\n```\n# It\'s very easy and usefl solution for all of you to understand .. so please upvote\n![th.jpeg](https://assets.leetcode.com/users/images/dedee7d2-6462-487b-a1d8-d6da80b19257_1709013818.618187.jpeg)\n
5
0
['Hash Table', 'Ordered Map', 'C', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript', 'C#']
1
check-if-number-has-equal-digit-count-and-digit-value
C++ || Easy || Explained || Map || ✅
c-easy-explained-map-by-tridibdalui04-m162
create a map to calculate the frequency\n2. iterate the string & check if frequncy is same with index+1 if not matched return false\n3. else return true\n\n\ncl
tridibdalui04
NORMAL
2022-10-21T17:47:40.851467+00:00
2022-10-21T17:47:40.851517+00:00
1,163
false
1. create a map to calculate the frequency\n2. iterate the string & check if frequncy is same with index+1 if not matched return false\n3. else return true\n\n```\nclass Solution {\npublic:\n bool digitCount(string s) {\n unordered_map<char, int>mp;\n for(int i=0;i<s.size();i++)\n mp[s[i]]++;\n for(int i=0; i<s.size(); i++)\n {\n char c=i+\'0\';\n if(mp[c]!=s[i]-\'0\')\n return false;\n }\n \n return true;\n }\n};\n```
5
0
['C']
0
check-if-number-has-equal-digit-count-and-digit-value
Brute-Force | C++ | Easy to understand
brute-force-c-easy-to-understand-by-itzy-00i1
\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<char,int> mp;\n for(int i=0;i<num.length();i++)\n {\n
itzyash_01
NORMAL
2022-05-28T16:08:27.713368+00:00
2022-05-28T16:08:27.713405+00:00
1,152
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<char,int> mp;\n for(int i=0;i<num.length();i++)\n {\n mp[num[i]]++;\n }\n for(auto ele: mp)\n {\n \n if(ele.second!=num[ele.first-\'0\']-\'0\')\n return false;\n }\n return true;\n \n }\n};\n```
5
0
['C', 'C++']
2
check-if-number-has-equal-digit-count-and-digit-value
Java | HashMap | String | Straightforward Solution
java-hashmap-string-straightforward-solu-uz4y
\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer,Integer> map = new HashMap<>();\n for(int i=0;i<num.length();i++
Divyansh__26
NORMAL
2022-09-20T06:26:55.664865+00:00
2022-09-20T06:26:55.664911+00:00
884
false
```\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer,Integer> map = new HashMap<>();\n for(int i=0;i<num.length();i++){\n int n = Character.getNumericValue(num.charAt(i));\n map.put(n,map.getOrDefault(n,0)+1);\n }\n for(int i=0;i<num.length();i++){\n if(map.containsKey(i)){\n int nn = map.get(i);\n if(nn!=Character.getNumericValue(num.charAt(i)))\n return false;\n }\n else{\n if(Character.getNumericValue(num.charAt(i))>0)\n return false;\n }\n }\n return true;\n }\n}\n```\nKindly upvote if you like the code.
4
0
['String', 'Counting', 'Java']
2
check-if-number-has-equal-digit-count-and-digit-value
⚠ Easy Python Solution using Hashmap ☢
easy-python-solution-using-hashmap-by-sa-rprr
\nclass Solution:\n def digitCount(self, num: str) -> bool:\n \n h = {}\n n = len(num)\n \n for i in range(n):\n
sanket_suryawanshi
NORMAL
2022-07-23T14:26:53.782254+00:00
2022-07-23T14:26:53.782318+00:00
363
false
```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n \n h = {}\n n = len(num)\n \n for i in range(n):\n h[i] = num[i]\n \n for i in h:\n if(num.count(str(i))!=int(h[i])):\n return 0\n \n return 1\n```
4
0
['Python']
1
check-if-number-has-equal-digit-count-and-digit-value
Easy Python Solution
easy-python-solution-by-vistrit-jnyo
\ndef digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i))!=int(num[i]):\n return False\n
vistrit
NORMAL
2022-06-02T00:04:06.945817+00:00
2022-06-02T00:04:06.945865+00:00
868
false
```\ndef digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i))!=int(num[i]):\n return False\n return True\n```
4
0
['Python', 'Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
O(N) solution
on-solution-by-shriyasankhyan-em4i
\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer,Integer> map = new HashMap<>();\n// First we are marking the f
shriyasankhyan
NORMAL
2022-05-30T07:16:53.545294+00:00
2022-05-30T07:22:27.747196+00:00
642
false
```\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer,Integer> map = new HashMap<>();\n// First we are marking the frequency for the number. As we are given in the question, num.charAt(i) is the\n// frequency of the number i in the num String.\n for(int number = 0; number < num.length(); number++){\n int frequency = Character.getNumericValue(num.charAt(number));\n map.put(number,frequency);\n }\n// Now we are traversing through the string.\n for(int index = 0; index< num.length(); index++) {\n// If character at index i is less than num.length(), then only we need to know its frequency.\n if (Character.getNumericValue(num.charAt(index)) < num.length()) {\n// Get the frequency of the number and subtract 1 from it if it is present.\n int frequency = map.get(Character.getNumericValue(num.charAt(index))) - 1;\n map.put(Character.getNumericValue(num.charAt(index)), frequency);\n }\n }\n// If all the values are 0 , then only it is right otherwise , the frequency is either more or less than the\n// specified frequency, hence return false;\n for (int i = 0; i < num.length(); i++) {\n if(map.get(i) !=0){\n return false;\n }\n }\n\n return true;\n }\n}\n```\nIf you liked the solution or found the solution unique , please upvote :)\nThank you
4
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
Python Easy solution
python-easy-solution-by-constantine786-g8tq
\nclass Solution:\n def digitCount(self, num: str) -> bool:\n counter=Counter(num)\n for i in range(len(num)):\n if counter[f\'{i}\'
constantine786
NORMAL
2022-05-28T16:18:38.486595+00:00
2022-05-28T16:18:38.486625+00:00
480
false
```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n counter=Counter(num)\n for i in range(len(num)):\n if counter[f\'{i}\'] != int(num[i]):\n return False\n return True\n```\n\n**Time - O(n)\nSpace - O(n)**\n\n---\n\n***Please upvote if you find it useful***
4
0
['Python', 'Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
Easiest Solution || 100% Beats🔥💯
easiest-solution-100-beats-by-aryaman123-qhw2
IntuitionCounting occurs of each digit of given string.Approach Make a frequency array counting number of occurence of each digit in given string Iterate over s
aryaman123
NORMAL
2025-03-17T15:18:08.651699+00:00
2025-03-17T15:18:08.651699+00:00
131
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Counting occurs of each digit of given string. # Approach <!-- Describe your approach to solving the problem. --> - Make a frequency array counting number of occurence of each digit in given string - Iterate over string num and return false if number of occurence at a given index is not equal to the digit at the index of string - If loop completes then return true; # Complexity - Time complexity:O(N) <!-- 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 digitCount(String num) { int freq[] = new int[10]; for(char c : num.toCharArray()){ freq[c-'0']++; } for(int i = 0 ; i<num.length(); i++){ if(freq[i]!= num.charAt(i)-'0'){ return false; } } return true; } } ```
3
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
Using a vector instead of map to reduce space complexity
using-a-vector-instead-of-map-to-reduce-9lqi1
Intuition\n Describe your first thoughts on how to solve this problem. \nUse a vector to keep track of all frequencies, and match it with the\nrequired frequenc
Lux27
NORMAL
2024-06-12T19:08:58.619417+00:00
2024-06-12T19:08:58.619439+00:00
75
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse a vector to keep track of all frequencies, and match it with the\nrequired frequencies.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Define a vector to of size 10, as there can be only 10 numbers (0 - 10) - we will use the index as key and vector space as value.\n* Loop through the given string once, counting all characters frequency.\n* Loop again in the string, check if value of frequencyRequired is equal to the given frequency, if not -- return false;\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTwo loops - O(n) + O(n) --> O(n);\nn : size of num\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nA vector of size 10 - O(10)\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n vector<int> freq(10, 0);\n\n for(char c : num){\n freq[c - \'0\']++;\n }\n\n for(int i = 0; i < num.size(); i++){\n // int requiredFreq = num[i] - \'0\';\n if(num[i] - \'0\' != freq[i]){\n return false;\n }\n }\n\n return true;\n }\n};\n```
3
0
['C++']
0
check-if-number-has-equal-digit-count-and-digit-value
easy cpp solution
easy-cpp-solution-by-vaibhav_2077-l5ku
\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int>mp;\n for(int i=0;i<num.size();i++){\n mp[num[i]
vaibhav_2077
NORMAL
2024-04-16T20:31:36.506272+00:00
2024-04-16T20:31:36.506290+00:00
439
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int>mp;\n for(int i=0;i<num.size();i++){\n mp[num[i]-\'0\']++;\n }\n \n for(int i=0;i<num.size();i++){\n \n if(mp[i]==num[i]-\'0\') continue;\n else return false;\n }\n return true;\n }\n};\n```
3
0
['C++']
1
check-if-number-has-equal-digit-count-and-digit-value
Simple Solution
simple-solution-by-adwxith-97mp
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
adwxith
NORMAL
2023-12-14T06:09:15.224079+00:00
2023-12-14T06:09:15.224113+00:00
132
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/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n const arr= Array(num.length).fill(0)\n for(let elem of num){\n arr[elem]++\n }\n return arr.join(\'\') == num\n};\n```
3
0
['JavaScript']
1
check-if-number-has-equal-digit-count-and-digit-value
python3 easy solution beats 99%, clean code
python3-easy-solution-beats-99-clean-cod-6ekv
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
ResilientWarrior
NORMAL
2023-08-07T13:08:42.288872+00:00
2023-08-07T13:08:42.288895+00:00
45
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)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n # both time and space effiecent\n arr = []\n check = []\n index = 0\n for i in num:\n temp = int(i)\n arr.append(temp)\n for j in range(temp):\n check.append(index)\n index +=1\n check.sort()\n arr.sort()\n return arr == check\n\n\n\n\n \n```
3
0
['Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
EASY JAVA BEATS 99%
easy-java-beats-99-by-thisisdhruvchopra-nup3
Intuition\nconsidering {1210}\n\n HASHMAP :\n\n {\n 0:1\n 1:2\n 2:3\n }\n\n index : 0 1 2 3\n number: 1 2 1 0\n\n accordi
thisisdhruvchopra
NORMAL
2023-04-20T10:56:32.742449+00:00
2023-04-20T10:56:32.742486+00:00
799
false
# Intuition\nconsidering {1210}\n\n HASHMAP :\n\n {\n 0:1\n 1:2\n 2:3\n }\n\n index : 0 1 2 3\n number: 1 2 1 0\n\n according to the question,\n\n num[i] should be equal to frequency of index i\n\n let x = num.charAt(i)\n convert character to integer using -\n int a = x - \'0\';\n\n thus, if(a != frequency of a) i.e if(a != map.get(i)) return false;\n\n\n but to avoid null pointer exception, we must check if the hashmap contains all indices or not, if it doesnt, then num[i] must be 0 as in this case,\n\nindex 3 is not in hashmap {\n 0:1\n 1:2\n 2:3\n }\n\nso , if it doesnot contain in hashmap (! map.containsKey(i))\n\nthen check if num[i] must be 0, else return false;,\nif it is 0, then continue\n\n# Time Complexity - O(n)\n# Space Complexity - O(n)\n\n# Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n\n //creating an integer - integer hashmap\n\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for(int i = 0; i < num.length(); i++)\n {\n char x = num.charAt(i);\n\n int a = x - \'0\'; // to create character to integer\n\n if(map.containsKey(a))\n map.put(a,map.get(a)+1);\n\n else\n map.put(a,1);\n\n }\n\n for(int i = 0; i<num.length(); i++)\n {\n\n // to avoid nullPointerException\n\n if(!map.containsKey(i))\n {\n if(num.charAt(i)!=\'0\') //it must be 0, else false\n return false;\n else //if it is 0, then continue\n continue;\n }\n char x = num.charAt(i); //let num[i] = x\n int a = x - \'0\'; //convert x to int\n if(a!=map.get(i)) //check if its equal to frequency\n return false;\n\n }\n\n return true;\n }\n}\n```
3
0
['Hash Table', 'Java']
1
check-if-number-has-equal-digit-count-and-digit-value
simple java solution
simple-java-solution-by-bhupendra082002-np05
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
bhupendra082002
NORMAL
2023-03-31T17:38:31.601560+00:00
2023-03-31T17:38:31.601592+00:00
488
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```\nclass Solution {\n public boolean digitCount(String num) {\n int[]arr = new int[10];\n\n for(int i=0;i<num.length();i++){\n arr[num.charAt(i)-\'0\']+=1;\n }\n //System.out.println(Arrays.toString(arr));\n \n\n for(int i=0;i<num.length();i++){\n if(arr[i]!=num.charAt(i)-\'0\'){\n return false;\n }\n }\n return true;\n \n }\n}\n```
3
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
JAVA || SOLUTION
java-solution-by-imranalikhan417-1f3s
\n\n# Code\n\nclass Solution {\n public boolean digitCount(String num) {\n final char[] digit = num.toCharArray(); // convert string to char array\n fina
imranalikhan417
NORMAL
2023-03-11T04:07:04.692853+00:00
2023-03-11T04:07:04.692877+00:00
686
false
\n\n# Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n final char[] digit = num.toCharArray(); // convert string to char array\n final int n = digit.length; // length of char array\n int[] count = new int[10]; // count arr length 10 because constraint 1<=n<=10\n for (char c : digit) {\n count[c - \'0\']++; // count of digits \n }\n for (int i = 0; i < n; i++) {\n if (digit[i] - \'0\' != count[i]) { // check \n return false;\n }\n }\n\n return true;\n }\n}\n\n// DRY RUN TO CLEARLY UNDERSTAND THE WORKING OF CODE \n```
3
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
python fast solution (faster than 93%)
python-fast-solution-faster-than-93-by-a-s92d
\n\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n base = {}\n for i in range(len(num)):\n if base.get(num[i], None)
a-miin
NORMAL
2022-06-05T18:00:58.703789+00:00
2022-06-05T18:00:58.703821+00:00
317
false
![image](https://assets.leetcode.com/users/images/2cc0a03a-545f-4144-a1be-d86804fc0d45_1654452047.1386557.png)\n\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n base = {}\n for i in range(len(num)):\n if base.get(num[i], None) is None:\n base[num[i]]=1\n else:\n base[num[i]]+=1\n if base.get(str(i), None) is None:\n base[str(i)]=0\n \n for i in range(len(num)):\n if str(base[str(i)])!=num[i]:\n return False\n return True\n```
3
0
['Python']
0
check-if-number-has-equal-digit-count-and-digit-value
C++ || Easy-to-understand
c-easy-to-understand-by-pitbull_45-0byl
\nclass Solution {\npublic:\n bool digitCount(string num) {\n int n=num.length();\n map<int,int> mp;\n for(int i=0;i<n;i++){\n
Pitbull_45
NORMAL
2022-05-28T19:12:59.782432+00:00
2022-05-28T19:12:59.782458+00:00
189
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n int n=num.length();\n map<int,int> mp;\n for(int i=0;i<n;i++){\n mp[num[i]-\'0\']++;\n }\n for(int i=0;i<n;i++){\n if(mp[i]!=num[i]-\'0\'){\n return false;\n }\n }\n return true;\n }\n};\n```
3
0
[]
0
check-if-number-has-equal-digit-count-and-digit-value
simple java solution
simple-java-solution-by-anany_a-yk4i
\nclass Solution {\n public boolean digitCount(String num) {\n \n int[] result = new int[10];\n for(int i=0;i<num.length();i++)\n
Anany_a
NORMAL
2022-05-28T16:08:53.174086+00:00
2022-05-28T16:08:53.174125+00:00
582
false
```\nclass Solution {\n public boolean digitCount(String num) {\n \n int[] result = new int[10];\n for(int i=0;i<num.length();i++)\n {\n result[num.charAt(i)-\'0\']++;\n }\n \n for(int i=0;i<num.length();i++)\n {\n if(num.charAt(i)-\'0\'!=result[i])\n return false;\n }\n return true;\n }\n}\n```
3
0
['String', 'Java']
0
check-if-number-has-equal-digit-count-and-digit-value
JavaScript | Map
javascript-map-by-codered_jack-y16d
js\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n const numLength = num.length;\n const numArray = num.split(
codered_jack
NORMAL
2022-05-28T16:02:53.662447+00:00
2022-05-29T15:09:10.586475+00:00
213
false
```js\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n const numLength = num.length;\n const numArray = num.split(\'\').map(Number);\n let result = "";\n \n const numFreq = numArray.reduce((acc,item)=>acc.set(item,acc.get(item) + 1 || 1),new Map())\n \n for(let i=0;i<numLength;i++){\n result+=numFreq.get(i) || "0"; \n }\n \n return result === num\n};\n```
3
0
[]
1
check-if-number-has-equal-digit-count-and-digit-value
another code in c ||please like if it is good||
another-code-in-c-please-like-if-it-is-g-tenh
IntuitionApproachComplexity Time complexity: Space complexity: Code
2400033083
NORMAL
2025-03-21T04:41:09.765702+00:00
2025-03-21T04:41:09.765702+00:00
241
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 ```c [] bool digitCount(char * num) { int l = strlen(num); for(int i=0;i<l;i++) { int count = 0; for(int j = 0;j<l;j++) { if(i==num[j]-'0') count++; } if(count != num[i]-'0') return false; } return true; } ```
2
0
['C']
1
check-if-number-has-equal-digit-count-and-digit-value
short code in c
short-code-in-c-by-2400033083-5nrw
IntuitionApproachComplexity Time complexity: Space complexity: Code
2400033083
NORMAL
2025-03-21T04:33:28.886176+00:00
2025-03-21T04:33:28.886176+00:00
163
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 ```c [] #include <stdio.h> #include <string.h> int digitCount(char* num) { int len = strlen(num); for(int i = 0; i < len; ++i) { int freq = 0; for(int j = 0; j < len; ++j) { if(num[j] == '0' + i) { freq++; } } if(num[i] - '0' != freq) { // check if frequencies of digit i is equal to num[i] return 0; // false } } return 1; // true } ```
2
0
['C']
1
check-if-number-has-equal-digit-count-and-digit-value
stoi nhi chaheye uske bina kr skte num[i]-'0' technique :D
stoi-nhi-chaheye-uske-bina-kr-skte-numi-w907m
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
yesyesem
NORMAL
2024-08-23T15:55:21.850172+00:00
2024-08-23T15:55:21.850209+00:00
55
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```cpp []\nclass Solution {\npublic:\n bool digitCount(string num) {\n int arr[10]={0};\n\n for(int i=0;i<num.length();i++)\n {\n arr[num[i]-\'0\']++;\n }\nint c=0;\n for(int i=0;i<num.length();i++)\n {\n \n if(arr[i]==(num[i]-\'0\'))\n c++;\n \n\n }\n if(c==num.length()) \n return true;\n return false; \n }\n};\n```
2
0
['C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Very easy to understand. Beats 91.43%
very-easy-to-understand-beats-9143-by-ak-mjj5
Approach\nWe have only 10 digits, that\'s why it is not necessary use dictionary or other collections. It is not good approach. Counting number of digits to arr
Akhmadovich
NORMAL
2024-08-15T06:33:47.171402+00:00
2024-08-15T06:35:49.189878+00:00
30
false
# Approach\nWe have only 10 digits, that\'s why it is not necessary use dictionary or other collections. It is not good approach. Counting number of digits to array is convinient and easy to check for result at the end.\nBeats 91.43% of solutions in time, 68.57% of solutions in space complexity.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\npublic class Solution \n{\n public bool DigitCount(string num)\n {\n int[] digits = new int[10];\n\n for (int i = 0; i < num.Length; i++)\n {\n digits[num[i] - \'0\']++;\n }\n\n for (int i = 0; i < num.Length; i++)\n {\n if (digits[i] != num[i] - \'0\')\n {\n return false;\n }\n }\n\n return true;\n }\n}\n```
2
0
['C#']
0
check-if-number-has-equal-digit-count-and-digit-value
3 line solution
3-line-solution-by-muhsinachipra-6e93
Code\n\nvar digitCount = function (num) {\n let arr = Array(num.length).fill(0)\n for (const ele of num) arr[ele]++\n return arr.join(\'\') === num\n}\
muhsinachipra
NORMAL
2024-04-15T06:33:06.416087+00:00
2024-04-15T06:33:06.416118+00:00
65
false
# Code\n```\nvar digitCount = function (num) {\n let arr = Array(num.length).fill(0)\n for (const ele of num) arr[ele]++\n return arr.join(\'\') === num\n}\n```
2
0
['JavaScript']
0
check-if-number-has-equal-digit-count-and-digit-value
Best approach
best-approach-by-adhilalikappil-puuz
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
adhilalikappil
NORMAL
2024-04-15T05:56:54.567404+00:00
2024-04-15T05:56:54.567439+00:00
238
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/**\n * @param {string} num\n * @return {boolean}\n */\nconst digitCount = function (num) {\n\n const arr = num.split("");\n\n for (let i = 0; i < arr.length; i++) {\n let count = arr.filter((e) => i == e).length;\n\n if (Number(arr[i]) !== count) {\n return false;\n }\n }\n return true;\n \n};\n```
2
0
['JavaScript']
1
check-if-number-has-equal-digit-count-and-digit-value
Easy solution | Unordered map
easy-solution-unordered-map-by-garimapac-ff6z
\n# Code\n\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int> mpp;\n for(auto i:num){\n mpp[i-\'0\'
garimapachori827
NORMAL
2023-12-11T10:16:02.034750+00:00
2023-12-11T10:16:02.034783+00:00
198
false
\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int> mpp;\n for(auto i:num){\n mpp[i-\'0\']++;\n }\n for(int i=0;i<num.size();i++){\n if(num[i]-\'0\' != mpp[i]){\n return false;\n }\n }\n return true;\n }\n};\n```
2
0
['String', 'Ordered Map', 'C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Simple easy cpp solution beats 100% ✅✅
simple-easy-cpp-solution-beats-100-by-va-mito
\n\n# Code\n\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int> m;\n for(auto x : num){\n m[x-\'0\'
vaibhav2112
NORMAL
2023-09-28T15:23:57.168825+00:00
2023-09-28T15:23:57.168861+00:00
215
false
\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int> m;\n for(auto x : num){\n m[x-\'0\']++;\n }\n\n for(int i = 0 ; i < num.length();i++){\n int val = num[i] - \'0\';\n if(m[i] != val){\n return false;\n }\n }\n\n return true;\n\n }\n};\n```
2
0
['C++']
1
check-if-number-has-equal-digit-count-and-digit-value
java || 100% beats || 0(N) || ❤️
java-100-beats-0n-by-saurabh_kumar1-mp5r
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
saurabh_kumar1
NORMAL
2023-08-24T15:57:42.254212+00:00
2023-08-24T15:57:42.254229+00:00
816
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:0(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n char temp[] = new char[11];\n int temp1 = 0 , temp2 = 0;\n for(int i=0; i<num.length(); i++){\n char ch = num.charAt(i); temp1 = ch-\'0\';\n temp[temp1]++;\n }\n for(int i=0; i<num.length(); i++){\n char ch = num.charAt(i); temp2 = ch-\'0\';\n if(temp[i]!=temp2) return false;\n }\n return true;\n }\n}\n```
2
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
Easy Python solution
easy-python-solution-by-mark0g111-e3lz
\n\n# Code\n\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i)) != int(num[i]):\
mark0g111
NORMAL
2023-04-11T11:56:02.297012+00:00
2023-04-11T11:56:02.297040+00:00
283
false
\n\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i)) != int(num[i]):\n return False\n return True \n```
2
0
['Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
🔥🔥EASY BEGINNER FRIENDLY SOLUTION USING FREQUENCY HASHMAP !! 🔥🔥
easy-beginner-friendly-solution-using-fr-et6h
Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nfrom collections import Counter\nclass Solution:\n def digitCount(self, num: s
2003480100009_A
NORMAL
2023-03-30T15:23:34.959665+00:00
2023-03-30T15:23:34.959703+00:00
706
false
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def digitCount(self, num: str) -> bool:\n dic=Counter(num)\n c=0\n for i in range(len(num)):\n if dic[str(i)]==int(num[i]):\n c+=1\n \n if c==len(num):\n return 1\n return 0\n\n```
2
0
['Hash Table', 'Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
C++ Solution || Brute Force || Hash Table
c-solution-brute-force-hash-table-by-asa-7qi2
Approach : Brute Force\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\
Asad_Sarwar
NORMAL
2023-03-18T16:42:54.398558+00:00
2023-03-18T16:42:54.398594+00:00
716
false
# Approach : Brute Force\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n \n vector<int> v(10,0);\n for (int i = 0; i < num.size(); i++)\n v[num[i] - \'0\']++;\n\n for (int i = 0; i < num.size(); i++)\n if (num[i] - \'0\' != v[i])\n return false;\n\n return true;\n\n }\n};\n```\n# Approach : Hash Table\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n \n unordered_map<int, int> m;\n for (auto e : num)\n m[e - \'0\']++;\n\n for (int i = 0; i < num.size(); i++)\n if (m[i] != num[i] - \'0\')\n return false;\n return true;\n\n }\n};\n```
2
0
['C++']
1
check-if-number-has-equal-digit-count-and-digit-value
C++ || Easy || Simple
c-easy-simple-by-naoman-wpnr
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\no(k)\n\n# Code\n\nclass Solution {\npublic:\n bool digitCount(string nums) {\n unordered_
Naoman
NORMAL
2023-03-10T05:27:56.199304+00:00
2023-03-10T05:27:56.199340+00:00
329
false
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\no(k)\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string nums) {\n unordered_map<int,int>mp;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n mp[nums[i]-\'0\']++;\n }\n for(int i=0;i<n;i++)\n {\n if(mp[i]!=nums[i]-\'0\')\n return 0;\n }\n return 1;\n }\n};\n```
2
0
['C++']
1
check-if-number-has-equal-digit-count-and-digit-value
Easy C++ solution !! ✅
easy-c-solution-by-rahulsingh_r_s-2ztz
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
rahulsingh_r_s
NORMAL
2023-02-27T18:30:00.450967+00:00
2023-02-27T18:30:00.451038+00:00
1,025
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```\nclass Solution {\npublic:\n bool digitCount(string nums) {\n unordered_map<int,int>mp;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n mp[nums[i]-\'0\']++;\n }\n for(int i=0;i<n;i++)\n {\n if(mp[i]!=nums[i]-\'0\')\n return 0;\n }\n return 1;\n\n }\n};\n```
2
0
['C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Beats 99% - Easy Python Solution
beats-99-easy-python-solution-by-pranavb-via5
`\nclass Solution:\n def digitCount(self, num: str) -> bool:\n checked = set()\n i = 0\n while i < len(num):\n if num[i] not
PranavBhatt
NORMAL
2022-11-27T06:36:06.418873+00:00
2022-11-27T06:36:06.418916+00:00
777
false
```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n checked = set()\n i = 0\n while i < len(num):\n if num[i] not in checked:\n count = num.count(str(i))\n if int(num[i]) != count:\n return False\n else:\n checked.add(num[i])\n i += 1\n else:\n i += 1\n \n return True\n``
2
0
['Python']
0
check-if-number-has-equal-digit-count-and-digit-value
⬆️⬆️✅✅✅[java/c++] one-liner | 100.00% | 0 Ms | O(1) 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
javac-one-liner-10000-0-ms-o1-by-manojku-b5p8
UPVOTE PLEASE\n\ncpp:\n\n\n return unordered_set<string>{"1210", "2020" , "21200", "3211000", "42101000", "521001000", "6210001000"}.count(num);\n\t\n\tjava:
ManojKumarPatnaik
NORMAL
2022-09-11T07:14:35.586867+00:00
2022-09-11T07:14:55.743873+00:00
114
false
**UPVOTE PLEASE**\n```\ncpp:\n\n\n return unordered_set<string>{"1210", "2020" , "21200", "3211000", "42101000", "521001000", "6210001000"}.count(num);\n\t\n\tjava:\n\t\n\treturn new HashSet<String>(List.of("1210", "2020" , "21200", "3211000", "42101000", "521001000", "6210001000")).contains(num); \n```
2
0
['C', 'C++', 'Java']
0
check-if-number-has-equal-digit-count-and-digit-value
here is my solution->>:)
here-is-my-solution-by-re__fresh-zfn4
*plz upvote if you find my solution helpful***\n\nclass Solution:\n def digitCount(self, n: str) -> bool:\n l=len(n)\n for i in range(l):\n
re__fresh
NORMAL
2022-09-04T13:09:54.567002+00:00
2022-09-04T13:09:54.567050+00:00
205
false
*****plz upvote if you find my solution helpful*****\n```\nclass Solution:\n def digitCount(self, n: str) -> bool:\n l=len(n)\n for i in range(l):\n if n.count(str(i))!=int(n[i]):\n \n return False\n return True\n \n```
2
0
['Python']
1
check-if-number-has-equal-digit-count-and-digit-value
[Java] || Easy To Understand || 2 HashMaps
java-easy-to-understand-2-hashmaps-by-te-u99g
\nclass Solution {\n public boolean digitCount(String num) {\n // Create a map for given frequencies\n HashMap<Character, Integer> givenFreqMap
tejas27dhanani
NORMAL
2022-06-28T17:52:50.808751+00:00
2022-06-28T17:52:50.808796+00:00
442
false
```\nclass Solution {\n public boolean digitCount(String num) {\n // Create a map for given frequencies\n HashMap<Character, Integer> givenFreqMap = new HashMap<>();\n \n // Create a map to count frequencies manually\n HashMap<Character, Integer> countFreqMap = new HashMap<>();\n \n // Loop through num\n for(int i = 0; i < num.length(); i++){\n \n // We only want to put in map if value at index is not equals to 0\n // because 0 means it\'s not in the string so we do not need that\n if(num.charAt(i) != \'0\'){\n // Add to givenFreqMap convert the index to char and it\'s value from char to int\n givenFreqMap.put((char)(i+\'0\'), num.charAt(i) - \'0\');\n }\n }\n \n // Loop through num \n for(char c : num.toCharArray()){\n \n // Add to countFreqMap and count thier frequencies\n countFreqMap.put(c, countFreqMap.getOrDefault(c, 0) + 1);\n }\n \n // If the characters and its frequencies are same in both map then return true, else false\n return givenFreqMap.equals(countFreqMap);\n \n }\n}\n```
2
0
['Java']
1
check-if-number-has-equal-digit-count-and-digit-value
Python - Easy 2 Liner | Faster than 93% |
python-easy-2-liner-faster-than-93-by-as-n3pr
\nclass Solution:\n def digitCount(self, num: str) -> bool: \n for i in range(len(num)):\n if(num.count(str(i))!=int(num[i])): r
Ash990
NORMAL
2022-06-25T07:19:19.960100+00:00
2022-06-25T07:19:19.960141+00:00
133
false
```\nclass Solution:\n def digitCount(self, num: str) -> bool: \n for i in range(len(num)):\n if(num.count(str(i))!=int(num[i])): return False\n return True\n```\n***Pls upvote if you find it helpful***
2
0
['Python']
0
check-if-number-has-equal-digit-count-and-digit-value
📌Easy Java☕ solution using hashmap
easy-java-solution-using-hashmap-by-saur-7qis
```\nclass Solution {\n public boolean digitCount(String num) \n {\n HashMap hmap = new HashMap<>();\n for(char ch:num.toCharArray())\n
saurabh_173
NORMAL
2022-06-07T13:15:50.011225+00:00
2022-06-07T13:15:50.011264+00:00
309
false
```\nclass Solution {\n public boolean digitCount(String num) \n {\n HashMap<Integer,Integer> hmap = new HashMap<>();\n for(char ch:num.toCharArray())\n hmap.put(Character.getNumericValue(ch),hmap.getOrDefault(Character.getNumericValue(ch),0)+1);\n \n for(int i=0;i<num.length();i++)\n {\n if(hmap.get(i)!=null && hmap.get(i)!=Character.getNumericValue(num.charAt(i)))\n return false;\n else if(hmap.get(i)==null && Character.getNumericValue(num.charAt(i))!=0)\n return false;\n }\n return true;\n }\n}
2
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
Kotlin Short & Easy Solution 264ms, faster than 50.00%
kotlin-short-easy-solution-264ms-faster-cm35z
just do what the problem says, along with 1 edge case\n\nclass Solution {\n fun digitCount(num: String): Boolean {\n val map = num.groupingBy { it }.e
Z3ROsum
NORMAL
2022-06-02T01:58:39.539587+00:00
2022-06-02T01:58:39.539619+00:00
66
false
just do what the problem says, along with 1 edge case\n```\nclass Solution {\n fun digitCount(num: String): Boolean {\n val map = num.groupingBy { it }.eachCount()\n return num.indices.all {\n val count = map[(\'0\'..\'9\').toList()[it]] ?: 0\n count == num[it].toString().toInt()\n }\n }\n}\n```
2
0
['Kotlin']
1
check-if-number-has-equal-digit-count-and-digit-value
Rust solution
rust-solution-by-bigmih-pxv3
\nimpl Solution {\n pub fn digit_count(num: String) -> bool {\n let mut counter = [0; 10];\n let num_it = num.bytes().map(|b| (b - b\'0\') as u
BigMih
NORMAL
2022-05-29T09:45:10.763233+00:00
2022-05-29T09:45:10.763269+00:00
100
false
```\nimpl Solution {\n pub fn digit_count(num: String) -> bool {\n let mut counter = [0; 10];\n let num_it = num.bytes().map(|b| (b - b\'0\') as usize);\n num_it.clone().for_each(|idx| counter[idx] += 1);\n num_it.enumerate().all(|(i, idx)| counter[i] == idx)\n }\n}\n```
2
0
['Rust']
2
check-if-number-has-equal-digit-count-and-digit-value
Very easy C++ Solution , using 1 For loop 😴
very-easy-c-solution-using-1-for-loop-by-n0st
\nclass Solution {\npublic:\n bool digitCount(string num) {\n for(int i=0;i<num.length();i++){\n\t\t\t// int to char\n char ch = i + \'0\'
negiharsh12
NORMAL
2022-05-29T00:23:50.498990+00:00
2022-05-29T00:23:50.499015+00:00
210
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n for(int i=0;i<num.length();i++){\n\t\t\t// int to char\n char ch = i + \'0\';\n\t\t\t\n\t\t\t// count no. of occurance\n int req = count(num.begin(),num.end(),ch);\n\t\t\t\n\t\t\t// check the given condtion\n if(req!=(num[i]-\'0\')) return false;\n }\n return true;\n }\n};\n```
2
0
['C']
0
check-if-number-has-equal-digit-count-and-digit-value
Python | Easy & understanding solution
python-easy-understanding-solution-by-ba-yvf8
```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n n=len(num)\n \n for i in range(n):\n if(num.count(str(i))!=i
backpropagator
NORMAL
2022-05-28T18:21:57.747877+00:00
2022-05-28T18:21:57.747923+00:00
374
false
```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n n=len(num)\n \n for i in range(n):\n if(num.count(str(i))!=int(num[i])):\n return False\n \n return True
2
0
['Python', 'Python3']
0
check-if-number-has-equal-digit-count-and-digit-value
O(n) solution using MAP
on-solution-using-map-by-guptasim8-1pjy
\nclass Solution {\npublic:\n bool digitCount(string num) {\n map<int,int> m;\n int n=num.size();\n for(int i=0;i<n;i++){\n m
guptasim8
NORMAL
2022-05-28T16:25:02.483124+00:00
2022-05-28T16:25:02.483162+00:00
139
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n map<int,int> m;\n int n=num.size();\n for(int i=0;i<n;i++){\n m[num[i]-\'0\']++;\n }\n for(int i=0;i<n;i++ ){\n if(num[i]==\'0\'&&m.find(i)==m.end())continue;\n if(m.find(i)!=m.end()&&m[i]==(num[i]-\'0\'))continue;\n return false;\n }\n return true;\n }\n};\n```
2
0
['String']
0
check-if-number-has-equal-digit-count-and-digit-value
javascript counter 105ms
javascript-counter-105ms-by-henrychen222-xbr2
\nconst counter = (a_or_s) => { let m = new Map(); for (const x of a_or_s) m.set(x, m.get(x) + 1 || 1); return m; };\n\nconst digitCount = (a) => {\n let m =
henrychen222
NORMAL
2022-05-28T16:21:14.358297+00:00
2022-05-28T16:21:14.358345+00:00
521
false
```\nconst counter = (a_or_s) => { let m = new Map(); for (const x of a_or_s) m.set(x, m.get(x) + 1 || 1); return m; };\n\nconst digitCount = (a) => {\n let m = counter(a), n = a.length;\n for (let i = 0; i < n; i++) {\n let cnt = m.get(i + \'\') || 0\n if (a[i] != cnt) return false;\n }\n return true;\n};\n```
2
0
['JavaScript']
0
check-if-number-has-equal-digit-count-and-digit-value
Python3 very elegant and straightforward
python3-very-elegant-and-straightforward-xq7o
\n\n c = Counter(num)\n for idx, x in enumerate(num):\n if c[str(idx)] != int(x):\n return False\n return True\n
tallicia
NORMAL
2022-05-28T16:19:53.835994+00:00
2022-05-28T16:23:33.323883+00:00
316
false
\n```\n c = Counter(num)\n for idx, x in enumerate(num):\n if c[str(idx)] != int(x):\n return False\n return True\n```
2
0
['Python', 'Python3']
2
check-if-number-has-equal-digit-count-and-digit-value
brute force C++ 100%
brute-force-c-100-by-whitefang1-y6pg
class Solution {\npublic:\n bool digitCount(string num) {\n int count=0;\n bool ans=true;\n for(int i=0;i<num.size();i++){\n
whitefang1
NORMAL
2022-05-28T16:13:48.696286+00:00
2022-05-28T16:13:48.696313+00:00
199
false
class Solution {\npublic:\n bool digitCount(string num) {\n int count=0;\n bool ans=true;\n for(int i=0;i<num.size();i++){\n for(int j=0;j<num.size();j++){\n if((num[j]-\'0\')==i){\n count=count+1;\n }\n }\n if((num[i]-\'0\')!=count){\n ans=false; \n }\n count=0;\n }\n return ans;\n }\n};
2
0
['String', 'C']
0
check-if-number-has-equal-digit-count-and-digit-value
2 liner C++
2-liner-c-by-aniketbasu-nr0d
\nclass Solution {\npublic:\n bool digitCount(string num) {\n for(int i=0;i<num.size();i++) if(count(num.begin(),num.end(),(i+\'0\')) != num[i]-\'0\')
aniketbasu
NORMAL
2022-05-28T16:01:37.616856+00:00
2022-05-28T16:06:20.149108+00:00
537
false
```\nclass Solution {\npublic:\n bool digitCount(string num) {\n for(int i=0;i<num.size();i++) if(count(num.begin(),num.end(),(i+\'0\')) != num[i]-\'0\') return false;\n return true;\n }\n};\n```\n\n\n\n**With Using Extra space :** \n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<char,int> mpp;\n for(auto c : num) mpp[c]++;\n for(int i=0;i<num.size();i++){\n char c = (char)i+\'0\';\n if(num[i]-\'0\' != mpp[c]) return false;\n }\n return true;\n \n }\n};\n```
2
0
['C', 'C++']
1
check-if-number-has-equal-digit-count-and-digit-value
easy solution
easy-solution-by-haneen_ep-mllp
IntuitionApproachComplexity Time complexity: Space complexity: Code
haneen_ep
NORMAL
2025-03-25T10:41:12.261376+00:00
2025-03-25T10:41:12.261376+00:00
25
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 ```javascript [] /** * @param {string} num * @return {boolean} */ var digitCount = function (num) { let digitFreq = new Array(10).fill(0); for (let digit of num) { digitFreq[Number(digit)]++ }; for (let i = 0; i < num.length; i++) { if (Number(num[i]) !== digitFreq[i]) { return false; } } return true; }; ```
1
0
['JavaScript']
0
check-if-number-has-equal-digit-count-and-digit-value
brute Force 🎊
brute-force-by-varuntyagig-z886
Code
varuntyagig
NORMAL
2025-02-12T07:27:55.476627+00:00
2025-02-12T07:27:55.476627+00:00
136
false
# Code ```cpp [] class Solution { public: bool digitCount(string num) { for (int i = 0; i < num.length(); i++) { int count = 0; int value = num[i] - '0'; for (int j = 0; j < num.length(); j++) { if (i == num[j] - '0') { count += 1; } } if (count != value) { return false; } } return true; } }; ```
1
0
['String', 'Counting', 'C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Java | Straight-forward solution
java-straight-forward-solution-by-lizlin-8nke
IntuitionCount how many times each digit shows up in the string, then compare each digit to see if the actual amount of times it appears are the same as the des
lizlingng
NORMAL
2025-02-11T04:53:00.475482+00:00
2025-02-11T04:53:00.475482+00:00
150
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Count how many times each digit shows up in the string, then compare each digit to see if the actual amount of times it appears are the same as the desired amount of times # Approach <!-- Describe your approach to solving the problem. --> Same as intuition. Submission beats 100% runtime and 98.81% memory # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n): n referring to the length of the num String - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1): constant space # Code ```java [] class Solution { public boolean digitCount(String num) { int[] count = new int[10]; // Analyze num string digit by digit to count how many timees each digit shows up for (int index = 0; index < num.length(); index++) { char character = num.charAt(index); int countIdx = character - '0'; count[countIdx]++; } // Check if digit[index] shows up the desired amount of times. // Desired count is the current is the actual digit string at this index // Actual count is what we counted above for (int index = 0; index < num.length(); index++) { int desiredCount = num.charAt(index) - '0'; int actualCount = count[index]; if (actualCount != desiredCount) { return false; } } return true; } } ```
1
0
['Java']
0
check-if-number-has-equal-digit-count-and-digit-value
✅ C++ | Simple Code ✅
c-simple-code-by-jagdish9903-0j1c
Complexity Time complexity: O(N) Space complexity: O(1) Code
Jagdish9903
NORMAL
2025-01-16T17:44:14.485587+00:00
2025-01-16T17:44:14.485587+00:00
215
false
# Complexity - Time complexity: $$O(N)$$ - Space complexity: $$O(1)$$ # Code ```cpp [] class Solution { public: bool digitCount(string num) { int n = num.size(); vector<int> count(10, 0); for(int i = 0; i < n; i++) { count[num[i] - '0']++; } for(int i = 0; i < n; i++) { if(count[i] == (num[i] - '0')) continue; else return false; } return true; } }; ```
1
0
['Hash Table', 'String', 'Counting', 'C++']
0
check-if-number-has-equal-digit-count-and-digit-value
Optimal answer using 2 loops
optimal-answer-using-2-loops-by-saksham_-bmfq
Complexity Time complexity: O(n) Space complexity: O(1) Code
Saksham_Gupta_
NORMAL
2025-01-04T11:06:03.770866+00:00
2025-01-04T11:06:03.770866+00:00
170
false
<!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: ***O(n)*** <!-- 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 digitCount(String num) { int[] count = new int[10]; for(char c: num.toCharArray()){ count[c - '0']++; } for(int i=0; i<num.length(); i++){ if(count[i] != num.charAt(i) - '0'){ return false; } } return true; } } ```
1
0
['String', 'Java']
0
check-if-number-has-equal-digit-count-and-digit-value
leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3
leetcodedaybyday-beats-100-with-c-and-be-3cf2
IntuitionThe problem requires verifying if the frequency of each digit in the string matches the digit's value at the corresponding index. The task can be solve
tuanlong1106
NORMAL
2024-12-30T09:05:55.887595+00:00
2024-12-30T09:05:55.887595+00:00
236
false
# Intuition The problem requires verifying if the frequency of each digit in the string matches the digit's value at the corresponding index. The task can be solved by counting the frequency of digits and comparing it with the expected values. # Approach 1. **Count Frequencies**: - Use an array of size 10 to count the occurrences of each digit (0-9) in the given string. 2. **Validate Frequencies**: - Iterate over the string, and for each digit at index `i`, check if its frequency matches the value of the digit in the string at index `i`. 3. **Return Result**: - If all frequencies match the expected values, return `True`. Otherwise, return `False`. # Complexity - **Time Complexity**: - \(O(n)\), where \(n\) is the length of the string `num`. We iterate over the string twice (once for counting frequencies and once for validation). - **Space Complexity**: - \(O(1)\), as the frequency array is of constant size (10). # Code ```cpp [] class Solution { public: bool digitCount(string num) { int n = num.size(); vector<int> freq(10, 0); for (char c : num){ freq[c - '0']++; } for (int i = 0; i < n; i++){ if (freq[i] != (num[i] - '0')){ return false; } } return true; } }; ``` ```python3 [] class Solution: def digitCount(self, num: str) -> bool: n = len(num) freq = [0] * 10 for c in num: freq[int(c)] += 1 for i in range(n): if freq[i] != int(num[i]): return False return True ```
1
0
['C++', 'Python3']
0