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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
patching-array
|
Easy Python solution defeat 100%
|
easy-python-solution-defeat-100-by-heii0-bv38
|
Let\'s see a situation, for example the n is 10 and nums is empty, the optimal solution to "reach" 10 is 0 1 2 4 7 15, we can find the pattern that we start fro
|
heii0w0rid
|
NORMAL
|
2020-12-29T13:42:34.924491+00:00
|
2020-12-29T13:51:38.492051+00:00
| 340 | false |
Let\'s see a situation, for example the n is 10 and `nums` is empty, the optimal solution to "reach" 10 is `0 1 2 4 7 15`, we can find the pattern that we start from `stack = [0]`, the next number should be sum of stack plus 1 equal to 1, and put 1 into stack, it become [0, 1], then the next number should be 2, the stack should be [0, 1, 2]...\nThen what about if we have a 3 in nums? \n```\n1. [0]\n2. [0, 1]\n3. [0, 1, 2]\n4. [0, 1, 2, 4] # becase 4 is greater than 3 which we already have in nums, let\'s replace 4 with 3\n4. [0, 1, 2, 3]\n5. [0, 1, 2, 3, 7] # next step will reach target n=10!\n6. [0, 1, 2, 3, 7, 14]\n```\nIf current nums is >= nums[i], use nums[i] replace current number and add it into SUM until SUM is >= n.\n```\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ret = i = s = 0 # ret: return value, s: SUM\n while True:\n if s >= n:\n return ret\n if i < len(nums) and s + 1 >= nums[i]:\n s += nums[i]\n i += 1\n else:\n s += s + 1\n ret += 1\n```
| 3 | 0 |
['Python']
| 0 |
patching-array
|
Clean and simple solution [ Java ]
|
clean-and-simple-solution-java-by-aakash-rgez
|
Code\n\nclass Solution {\n public int minPatches(int[] nums, int n) {\n int minPatch = 0, i = 0, len = nums.length;\n long currentMaxValue = 0;
|
aakashmv23
|
NORMAL
|
2024-06-19T08:34:09.803382+00:00
|
2024-06-19T08:34:09.803408+00:00
| 12 | false |
# Code\n```\nclass Solution {\n public int minPatches(int[] nums, int n) {\n int minPatch = 0, i = 0, len = nums.length;\n long currentMaxValue = 0;\n\n while(currentMaxValue < n)\n {\n if(i < len && currentMaxValue+1 >= nums[i])\n {\n currentMaxValue += nums[i];\n ++i;\n } \n else\n {\n currentMaxValue += (currentMaxValue + 1);\n ++minPatch;\n }\n }\n return minPatch;\n }\n}\n```\n\n---\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---\n\n# Upvote if it helped \u2B06\uFE0F
| 2 | 0 |
['Java']
| 0 |
patching-array
|
Beats 100% in java hindi me asaan approach
|
beats-100-in-java-hindi-me-asaan-approac-z2ue
|
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
|
bakree
|
NORMAL
|
2024-06-16T13:23:15.487466+00:00
|
2024-06-16T13:23:15.487494+00:00
| 15 | 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)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n public int minPatches(int[] nums, int n) {\n long missing = 1; // Wo smallest number jo humein banana hai\n int patches = 0, i = 0; // patches count aur index i\n\n while (missing <= n) { // Jab tak missing n se chhota ya barabar hai\n if (i < nums.length && nums[i] <= missing) { \n // Agar current number missing se chhota ya barabar hai\n missing += nums[i++]; // Us number ko missing mein add karo aur index badhao\n } else {\n // Agar current number missing se bada hai ya array khatam ho gaya hai\n missing += missing; // missing ko add karo (double kar do)\n patches++; // patches count increment karo\n }\n }\n return patches; // Minimum patches return karo\n }\n}\n\n```
| 2 | 0 |
['Array', 'Java']
| 0 |
patching-array
|
Most optimal solution in java
|
most-optimal-solution-in-java-by-yash_ja-i34b
|
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
|
yash_jadaun
|
NORMAL
|
2024-06-16T07:14:49.025604+00:00
|
2024-06-16T07:14:49.025632+00:00
| 53 | 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 int minPatches(int[] nums, int n) {\n int i=0;\n int count=0;\n long sum=0;\n int len=nums.length;\n\n while(i<len&&sum<n){\n if(sum+1>=nums[i]){\n sum+=nums[i];\n i++;\n }\n else{\n count++;\n sum+=sum+1;\n System.out.println(sum);\n }\n }\n\n while(sum<n){\n sum=sum+sum+1;\n System.out.println(sum);\n count++;\n }\n return count; \n }\n}\n```
| 2 | 0 |
['Greedy', 'Java']
| 1 |
patching-array
|
C++ | 100% | Time complexity O(N) | Easy | Math | Simple
|
c-100-time-complexity-on-easy-math-simpl-l9ii
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\nThe goal is to ensure that we can form any number in the range [1, n] using the ele
|
gavnish_kumar
|
NORMAL
|
2024-06-16T07:07:01.127756+00:00
|
2024-06-16T07:07:01.127791+00:00
| 78 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\nThe goal is to ensure that we can form any number in the range [1, n] using the elements in the given sorted array nums and possibly adding the minimum number of additional patches. The main idea is to keep track of the current sum of the numbers we can form, and whenever we find a gap (i.e., a number we cannot form with the current sum), we add the smallest number that fills this gap.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Initialize Variables:**\n**sum** to keep track of the current range of numbers we can form, initially set to 0.\n**ans** to count the number of patches needed, initially set to 0.\n\n**Edge Case Check:**\nIf the first element of nums is not 1, we need to patch 1 to start forming numbers from 1.\n\n**Iterate Through nums:**\nFor each number in nums, check if the next number we need to form (i.e., sum + 1) is less than the current number in nums. If so, we need to add patches until sum + 1 is not less than the current number in nums.\n\n**Add Patches:**\nCalculate the number of patches needed to bridge the gap using log2((nums[i] - 1) / (sum + 1)) + 1.\nUpdate sum and ans accordingly by adding patches.\n\n**Handle Remaining Gap:**\nAfter iterating through nums, if sum is still less than n, add the necessary patches to cover the remaining gap.\nReturn the Result:\n\nFinally, return the number of patches needed.\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 int minPatches(vector<int>& nums, int n) {\n long long int sum=0;\n int ans=0;\n if(nums[0]!=1){\n sum=1;\n ans=1;\n }\n for(int i=0;i<nums.size();i++){\n int val= sum+1;\n if(sum>=n) return ans;\n if(val<nums[i]){\n int numberAdded = log2((nums[i]-1)/val)+1;\n for(int k=0;k<numberAdded;k++){\n sum+= val*pow(2,k);\n ans++;\n if(sum>=n) return ans;\n }\n }\n sum+= nums[i]; \n }\n if(sum<n){\n int val= sum+1;\n int numberAdded = log2(n/val)+1;\n sum=sum+ val*(pow(2,numberAdded)-1)+n;\n ans+= numberAdded;\n }\n return ans;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
patching-array
|
Easy to understand solution | 100% Beast | Greedy Approach | c++ | python | java
|
easy-to-understand-solution-100-beast-gr-gxwm
|
Intuition\nThe problem requires ensuring that every integer in the range [1, n] can be formed by the sum of some subset of elements from the given sorted array
|
umeshbhatiya143
|
NORMAL
|
2024-06-16T06:32:57.258607+00:00
|
2024-06-16T06:32:57.258636+00:00
| 75 | false |
# Intuition\nThe problem requires ensuring that every integer in the range [1, n] can be formed by the sum of some subset of elements from the given sorted array nums. If this is not possible, we need to determine the minimum number of additional numbers (patches) needed to achieve this.\n\nThe key intuition here is to maintain a running sum of the numbers that can be formed. By starting with the smallest number that cannot be formed (miss), we either use elements from nums if they can contribute to forming miss or patch the array by adding miss itself, thereby extending the range of numbers we can form.\n\n\n# Approach\n1. Initialization:\n - ***\'miss\'*** is initialized to ***\'1\'***, representing the smallest number we need to form.\n - ***\'i\'*** is initialized to ***\'0\'***, representing the current index in nums.\n - ***\'patch\'*** is initialized to ***\'0\'***, representing the number of patches needed.\n\n2. Main Loop:\n - The loop continues as long as ***\'miss\'*** is less than or equal to n.\n - If the current element in ***\'nums\'*** is less than or equal to ***\'miss\'***, we can use this element to form miss and increment ***\'miss\'*** by the value of this element. We also move to the next element in nums by incrementing i.\n - If the current element in nums is greater than ***\'miss\'*** or we have exhausted all elements in nums, we patch the array by adding ***\'miss\'*** to the range of numbers we can form and increment ***\'miss\'*** by ***\'miss\'***. We also increment the ***\'patch\'*** counter.\n# Complexity\n- Time complexity: **O(n)**, where ***\'n\'*** is the length of the nums array. \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# Example with Explanation:\nFor nums = [1, 2] and n = 10:\n\nStart with miss = 1, i = 0, patch = 0.\nnums[0] = 1 can form miss. Update miss = 1 + 1 = 2, increment i.\nnums[1] = 2 can form miss. Update miss = 2 + 2 = 4, increment i.\nNo more elements in nums, so patch with miss = 4. Update miss = 4 + 4 = 8, increment patch = 1.\nStill no more elements, patch with miss = 8. Update miss = 8 + 8 = 16, increment patch = 2.\nmiss = 16 is greater than n = 10, stop.\n\n**The minimum number of patches required is 2.**\n# Code\n```c++ []\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n int patch = 0;\n long long miss = 1;\n int i = 0;\n \n while(miss<=n){\n if(i<nums.size() and nums[i] <= miss){\n miss += nums[i];\n i++;\n }\n else { // if((i<nums.size() and nums[i]>miss) or i>nums.size())\n patch++;\n miss += miss;\n }\n }\n\n return patch;\n }\n};\n```\n```python []\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n patches = 0\n miss = 1\n i = 0\n \n while miss <= n:\n if i < len(nums) and nums[i] <= miss:\n miss += nums[i]\n i += 1\n else:\n patches += 1\n miss += miss\n \n return patches\n \n```\n```Java []\nclass Solution {\n public int minPatches(int[] nums, int n) {\n int patches = 0;\n long miss = 1;\n int i = 0;\n\n while (miss <= n) {\n if (i < nums.length && nums[i] <= miss) {\n miss += nums[i];\n i++;\n } else {\n patches++;\n miss += miss;\n }\n }\n\n return patches;\n }\n}\n```\n
| 2 | 0 |
['Array', 'Greedy', 'Python', 'C++', 'Java', 'Python3']
| 1 |
patching-array
|
✏️ 100%Beats 💯 || 5 Language 🚀|| 🪩🫧Best visualization🎯|| Best formatted🍸🥂🫧✧˖°|
|
100beats-5-language-best-visualization-b-s0mh
|
\uD83C\uDF89 Screenshot \uD83D\uDCF8\n\n\n\n\n## Input \uD83D\uDCE5 \n\n One Sorted* Number Array (nums) & (N) \n\n 1 <= nums[i] <= 10^4\n\n 1 <= N <=
|
Prakhar-002
|
NORMAL
|
2024-06-16T05:25:45.499831+00:00
|
2024-06-16T05:25:45.499882+00:00
| 195 | false |
# \uD83C\uDF89 Screenshot \uD83D\uDCF8\n\n\n\n\n## Input \uD83D\uDCE5 \n\n One Sorted* Number Array (nums) & (N) \n\n 1 <= nums[i] <= 10^4\n\n 1 <= N <= 2^31 - 1\n\n\n## Output \uD83D\uDCE4\n\n We have to count number of patches (added number) by which \n\n our array subArray sum become in (Range[1, N]) \n\n Means by adding any number we got sum 1 <= Sum <= N\n\n\n# Intuition \uD83E\uDD14\uD83D\uDCAD\n\n\n We are given number array so we just have to count number of\n\n patches so that sum of any number of our arr become 1 <= Sum <= N\n\n\n\n# Example \uD83D\uDCDC\n\n `Ex.`\n\n nums = [1, 3], n = 6 \n\n 1. arr = [1]; reach = 1; pactes = 0 \n \n add 2 to our array\n\n 2. arr = [1, 2] maxNumReach = 3 (1 + 2) pactes = 1 \n\n add 3 to our array\n \n 3. arr = [1, 2, 3] maxNumReach = 6 (1 + 2 + 3) pactes = 1 \n\n\n\n# Approach \u270D\uD83C\uDFFC\n \n we have to make our subarray sum to max untill we reach given N\n\n By either adding our own elements or elemets giving in array \n\n So if we add 1 number from given in array we can reach \n\n upto perivous reach + adding that number \n\n cause we had our maxSum of sub Array before so if \n\n we are adding another element It can reach upto \n\n previous + current adding element \n\n and if we don\'t add any number given in nums array \n\n The max possible element we can add is ourself cause we have to \n\n maximize our sum and catch is we\'ve to addd given array element \n\n so once we exceed number present at Ith after adding ourself \n\n to maximize we will add that number too just to minimize \n \n The patches cause adding another ourself inc patche by one\n\n\n### I think you all got the idea so let\'s just go step by step\n\n\n# Step wise \uD83E\uDE9C\n\n\n There will be 3 steps \n\n Step 1 \u27A4 Take three var i = 0, reach = 1, patches = 0 \n\n \u2022 we assign reach = 1 cause we have to go { 1 <= N }\n\n \u2022 cause adding elem will be a very long number so we\'ll make \n\n \u2022 our (Reach A Long Number)\n\n Step 2 \u27A4 apply while loop until we get reach <= n \n\n \u2022 To inc our reach we have two option \n\n Option 1 \u27A4 add nums\'s number \n\n \u2022 If we exceed our reach by Ith number \n\n -> consider that we should have elem in nums\n\n \u2022 We will add number to our reach\n\n Option 2 \u27A4 add our self and inc patches by 1\n\n \u2022 We just inc our reach by adding ourself\n\n Step 3 \u27A4 return patches\n\n\n\n\n# Complexity \uD83C\uDFD7\uFE0F\n- \u231A Time complexity: $$O(n)$$ `n = given`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- \uD83E\uDDFA Space complexity: $$O(1)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code \uD83D\uDC68\uD83C\uDFFB\u200D\uD83D\uDCBB\n\n``` JAVA []\nclass Solution {\n public int minPatches(int[] nums, int n) {\n // REACH is number up to which we can add our number and got value\n long reach = 1;\n int i = 0;\n int patches = 0;\n\n // we have to go up to given n so we\'ll loop for reach until it reaches n\n while (reach <= n) {\n // if we exceed the value present in array\n if (i < nums.length && nums[i] <= reach) {\n // we\'ll add our array value\n reach += nums[i++];\n } else {\n // else we\'ll keep adding ourself to reach (N)\n reach += reach;\n // If we add ourself mean we added a number to array hence we inc our patches\n // count\n patches++;\n }\n }\n\n return patches;\n }\n}\n``` \n``` C++ []\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n // REACH is number up to which we can add our number and got value\n long long reach = 1;\n long long patches = 0;\n long i = 0;\n\n // we have to go up to given n so we\'ll loop for reach until it reaches\n // n\n while ((reach <= n)) {\n // if we exceed the value present in array\n if (i < nums.size() && nums[i] <= reach) {\n // we\'ll add our array value\n reach += nums[i++];\n } else {\n // else we\'ll keep adding ourself to reach (N)\n reach += reach;\n // If we add ourself mean we added a number to array hence we\n // inc our patches count\n patches++;\n }\n }\n return patches;\n }\n};\n```\n``` JAVASCRIPT []\nvar minPatches = function (nums, n) {\n // REACH is number up to which we can add our number and got value\n let reach = 1;\n let i = 0;\n let patches = 0;\n\n // we have to go up to given n so we\'ll loop for reach until it reaches n \n while (reach <= n) {\n // if we exceed the value present in array \n if (i < nums.length && nums[i] <= reach) {\n // we\'ll add our array value \n reach += nums[i++];\n } else {\n // else we\'ll keep adding ourself to reach (N)\n reach += reach;\n // If we add ourself mean we added a number to array hence we inc our patches count\n patches++;\n }\n }\n\n return patches;\n};\n```\n```PYTHON []\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n # REACH is number up to which we can add our number and got value\n reach = 1\n i = 0\n patches = 0\n\n # we have to go up to given n so we\'ll loop for reach until it reaches n\n while reach <= n:\n # if we exceed the value present in array\n if i < len(nums) and nums[i] <= reach:\n # we\'ll add our array value\n reach += nums[i]\n i += 1\n else:\n # else we\'ll keep adding ourself to reach (N)\n reach += reach\n # f we add ourself mean we added a number to array hence we inc our patches count\n patches += 1\n\n return patches\n\n```\n```C []\nint minPatches(int* nums, int numsSize, int n) {\n // REACH is number up to which we can add our number and got value\n long long reach = 1;\n long long patches = 0;\n long i = 0;\n\n // we have to go up to given n so we\'ll loop for reach until it reaches n\n while ((reach <= n)) {\n // if we exceed the value present in array\n if (i < numsSize && nums[i] <= reach) {\n // we\'ll add our array value\n reach += nums[i++];\n } else {\n // else we\'ll keep adding ourself to reach (N)\n reach += reach;\n // If we add ourself mean we added a number to array hence we inc\n // our patches count\n patches++;\n }\n }\n return patches;\n}\n```\n\n---\n# \uD83E\uDD42\u2728\uD83E\uDDC1 More solution \uD83C\uDF89\uD83C\uDF82\u2728\uD83C\uDF70\uD83E\uDD73 \n\n## Go To My Profile and access my GIT [Prakhar-002](https://leetcode.com/u/Prakhar-002/)\n\n## JAVA \uD83C\uDF41| PYTHON \uD83C\uDF70| JAVASCRIPT\u2603\uFE0F | C++ \uD83C\uDFB2| C \uD83D\uDC96\n\n\n\n
| 2 | 0 |
['Array', 'Greedy', 'C', 'C++', 'Java', 'Python3', 'JavaScript']
| 1 |
patching-array
|
0ms
|
0ms-by-anil-budamakuntla-d8r4
|
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
|
ANIL-BUDAMAKUNTLA
|
NORMAL
|
2024-06-16T05:14:51.565427+00:00
|
2024-06-16T05:19:36.353855+00:00
| 12 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(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 long long minPatches(vector<int>& a, int n) {\n\n long long i,j=0,ans=0,k=0,m;\n a.push_back(INT_MAX);\n\n for(i=0;i<a.size();i++)\n {\n if(a[i]>n)a[i]=n+1;\n if(a[i]>k)\n {\n j=k+1;\n m=a[i]-1;\n while(k<m)\n {\n k+=k+1;\n ans++;\n\n\n }\n\n }\n \n k+=a[i];\n if(k>=n) break;\n }\n return ans;\n \n }\n};\n```\n\n
| 2 | 0 |
['C++']
| 1 |
patching-array
|
beats 100% in time,96% in space. | | easy to understand| |
|
beats-100-in-time96-in-space-easy-to-und-8yyg
|
Intuition\n Describe your first thoughts on how to solve this problem. \nthere is no intution i just wrote in page and got a pattern.\n# Approach\n Describe you
|
vedant_verma786
|
NORMAL
|
2024-06-16T04:56:11.175844+00:00
|
2024-06-16T04:56:11.175868+00:00
| 306 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**there is no intution i just wrote in page and got a pattern.**\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we took `howmanypatch=0` to store number of elements to patch,`elementToSearch=1` we will search for this element as long as this doesnt equal to or greater then n.\n\n- we check if element exist in the array or not if it doesnt exist it means we need that element so in else statement we add that element in orginal element you can also multiply it by 2 `elementToSearch*=elementToSearch`.\n\n- if we pay attention lets suppose [1] as array max you can get is 1;\n- [1,2] max you can get is 3;\n- [1,2,4] max you can get is 7;\n- if you pay attention here when you put natural numbers in array in non-decreasing manner and each next elment is 2* of last element,than you can create all the elements from [1,sumofallelements].\n- for example:[1,2,4,8,16,32] n=45 ,sum=63,you can create all the elements from range [1,63] as 45 comes in between we can also create it from these elements.\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 {\n public int minPatches(int[] nums, int n) {\n int howmanytopatch=0;\n long elementToSearch=1;\n \n int lengthpointer=0;\n while(elementToSearch<=n){\n if(lengthpointer<nums.length && elementToSearch>=nums[lengthpointer]){\n elementToSearch+=nums[lengthpointer];\n lengthpointer++;\n }\n else{\n howmanytopatch++;\n elementToSearch+=elementToSearch;\n }\n }\n return howmanytopatch;\n \n }\n}\n```
| 2 | 0 |
['Array', 'Dynamic Programming', 'Java']
| 3 |
patching-array
|
[Kotlin]O[n] This is not hard problem, just some calculation
|
kotlinon-this-is-not-hard-problem-just-s-5u68
|
Intuition\nNaive thought\n[1] covers range 1-> 1\n[1, 2] covers range 1-> 3\n[1, 2, 4] covers range 1-> 7\n[1, 2, 4, 8] covers range 1-> 15\n\n\nNaive thought\n
|
anhtrungcuccua1
|
NORMAL
|
2024-06-16T04:51:50.004515+00:00
|
2024-06-16T04:51:50.004541+00:00
| 63 | false |
# Intuition\nNaive thought\n[1] covers range 1-> 1\n[1, 2] covers range 1-> 3\n[1, 2, 4] covers range 1-> 7\n[1, 2, 4, 8] covers range 1-> 15\n\n\nNaive thought\n[1] covers range 1-> 1\n[1, 2] covers range 1-> 3\n**[1, 2, 2]** covers range 1-> 5\n[1, 2, 2, 3] covers range 1-> 8\n\n# Code\n```\nclass Solution {\n fun minPatches(nums: IntArray, n: Int): Int {\n var total = 0L\n var count = 0L\n var i = 0\n while (total < n){\n val expectNext = total + 1\n if (i < nums.size){\n if (nums[i] <= expectNext){\n total += nums[i]\n i++\n } else{\n count ++\n total += expectNext\n }\n } else{\n count ++\n total += expectNext\n }\n }\n\n return count.toInt()\n }\n}\n```
| 2 | 0 |
['Kotlin']
| 1 |
patching-array
|
A robust solution in python#
|
a-robust-solution-in-python-by-anand_shu-4sfa
|
Intuition\nTo solve the problem of determining the minimum number of patches required to ensure that every number in the range \n[1,n] can be formed by the sum
|
anand_shukla1312
|
NORMAL
|
2024-06-16T03:08:50.730344+00:00
|
2024-06-16T03:08:50.730378+00:00
| 19 | false |
# Intuition\nTo solve the problem of determining the minimum number of patches required to ensure that every number in the range \n[1,n] can be formed by the sum of some elements in the sorted array nums, we can use a greedy algorithm.\n# Approach\n**Key Idea:**\nWe maintain a variable *miss* which represents the smallest number that cannot be formed with the current set of elements in nums. Initially, miss is set to 1.\n\nWe iterate through the array and for each number num:\n\n 1) If num is less than or equal to miss, it means we can extend the range of numbers we can form to at least miss + num - 1.\n 2) If num is greater than miss, it means we need to add a number equal to miss to cover the gap.\n\nWe repeat this process until miss exceeds n.\n\nSteps:\n\n1) Initialize miss to 1 and a counter patches to 0.\n2) Iterate through the array nums and for each number:\n => If num is less than or equal to miss, update miss to miss + num.\n =>If num is greater than miss, increment patches, add miss to cover the gap, and update miss to miss * 2.\n3) Continue this process until miss exceeds n.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: \nO(logn) in the worst case, making it efficient for large values of n.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n1. Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n patches = 0\n miss = 1\n i = 0\n \n while miss <= n:\n if i < len(nums) and nums[i] <= miss:\n miss += nums[i]\n i += 1\n else:\n miss += miss\n patches += 1\n \n return patches\n\n\n```
| 2 | 0 |
['Iterator', 'Python3']
| 0 |
patching-array
|
100% BEATS|| EASY MATHS SOLUTION
|
100-beats-easy-maths-solution-by-anubhav-mzgk
|
Intuition\nIt\'s totally a mathematics problem.In maths if you can achieve any combination certain sum,and get a number sum+1,then you can make any sum combinat
|
anubhavkrishna
|
NORMAL
|
2024-06-16T02:27:27.504850+00:00
|
2024-06-16T02:27:27.504873+00:00
| 31 | false |
# Intuition\nIt\'s totally a mathematics problem.In maths if you can achieve any combination certain sum,and get a number sum+1,then you can make any sum combinations from 1 to sum*2+1\n\n# Approach\nIf the next element is not sum+1,then add sum+1 and your range becomes sum*2+1 else you can add smaller number to increase your range,but not a greater number than sum+1\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n int ans=0;ll ml=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]<=ml+1){\n ml+=nums[i];\n }\n else{\n while(nums[i]>ml+1){\n ml+=(ml+1);\n ans++;\n if(ml>=n)break;\n }\n ml+=nums[i];\n }\n if(ml>=n)break;\n }\n while(ml<n){\n ml+=ml+1;\n ans++;\n }\n return ans;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
patching-array
|
C++ | | Easy Solution
|
c-easy-solution-by-donut_7-hbbq
|
Intuition\n###### Given a sorted array nums and an integer n, determine the minimum number of additional elements needed so that any number from 1 to n can be f
|
Donut_7
|
NORMAL
|
2024-06-16T01:57:16.510615+00:00
|
2024-06-16T01:57:16.510633+00:00
| 9 | false |
# Intuition\n###### Given a sorted array `nums` and an integer `n`, determine the minimum number of additional elements needed so that any number from 1 to `n` can be formed as the sum of some elements in the array.\n\n---\n\n\n# Approach\n\n### Approach\n1. **Initialization**: \n - Set `sum = 0` to track the maximum sum achievable.\n - Set `res = 0` to count the number of patches needed.\n - Use `i = 0` to iterate through `nums`.\n\n2. **Iteration**:\n - While `sum < n`, check if the next element in `nums` can extend `sum`:\n - If `nums[i] <= sum + 1`, add `nums[i]` to `sum` and increment `i`.\n - If `nums[i] > sum + 1`, add a patch (`sum + 1`) to cover the gap and increment `res`.\n\n\n---\n\n\n\n# Complexity\n##### Time complexity: $$O(n)$$\n\n##### Space complexity: $$O(1)$$\n\n---\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n long long sum = 0;\n int res = 0;\n int i = 0;\n\n while (sum < n) {\n if (i < nums.size() && nums[i] <= sum + 1) {\n sum += nums[i];\n i++;\n } else {\n sum += (sum + 1);\n res++;\n }\n }\n\n return res;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
patching-array
|
Easy Peasy 🔥|0 ms | Java || C||| Python
|
easy-peasy-0-ms-java-c-python-by-ravipar-m6gs
|
\npublic class Solution {\n public int minPatches(int[] nums, int n) {\n long miss = 1;\n int i = 0;\n int patches = 0;\n\n while
|
raviparihar_
|
NORMAL
|
2024-06-16T00:36:24.865555+00:00
|
2024-06-16T14:41:34.763287+00:00
| 336 | false |
```\npublic class Solution {\n public int minPatches(int[] nums, int n) {\n long miss = 1;\n int i = 0;\n int patches = 0;\n\n while (miss <= n) {\n if (i < nums.length && nums[i] <= miss) {\n miss += nums[i];\n i++;\n } else {\n miss += miss;\n patches++;\n }\n }\n\n return patches;\n }\n}\n\n```\n\n```\nint minPatches(int* nums, int numsSize, int n) {\n long miss = 1;\n int i = 0;\n int patches = 0;\n\n while (miss <= n) {\n if (i < numsSize && nums[i] <= miss) {\n miss += nums[i];\n i++;\n } else {\n miss += miss;\n patches++;\n }\n }\n\n return patches;\n}\n \xA0 \xA0}\n```\n```\ndef min_patches(nums, n):\n miss = 1\n i = 0\n patches = 0\n\n while miss <= n:\n if i < len(nums) and nums[i] <= miss:\n miss += nums[i]\n i += 1\n else:\n miss += miss\n patches += 1\n\n return patches\n```
| 2 | 0 |
['C', 'Python', 'Java']
| 2 |
patching-array
|
✅ Beginner Friendly with detailed Explanation
|
beginner-friendly-with-detailed-explanat-t9px
|
Intuition\nWhen dealing with an array of integers, the goal is to determine the minimum number of patches (additional numbers) required so that every number fro
|
lebon
|
NORMAL
|
2024-06-16T00:24:54.134138+00:00
|
2024-06-16T00:24:54.134158+00:00
| 55 | false |
# Intuition\nWhen dealing with an array of integers, the goal is to determine **the minimum number of patches (_additional numbers_)** required so that every number from 1 to `n` can be formed by the sum of some subset of the array. Initially, it seems feasible to check all combinations, but this would be inefficient. Instead, we can use a greedy approach to iteratively cover the next missing number.\n\n# Approach\n1. **Initialization**:\n - Start with `missingNumber` set to 1. This variable represents the smallest number that cannot currently be formed using the numbers in the array or the patches added.\n - Use `patchesCount` to count the number of patches (new numbers) added.\n - Use `index` to iterate through the `nums` array.\n\n2. **Iterate Until All Numbers Up to `n` Can Be Formed**:\n - Continue the loop while `missingNumber` is less than or equal to `n`.\n - If the current number in `nums` (at `index`) is less than or equal to `missingNumber`, add this number to `missingNumber` (since it helps cover the missing number) and increment the `index`.\n - If the current number in `nums` is greater than `missingNumber`, add `missingNumber` itself to cover the gap. This doubles `missingNumber` and increments `patchesCount` since we added a new patch.\n\n3. **Return the Result**:\n - After the loop, `patchesCount` will contain the number of patches added to ensure all numbers from 1 to `n` can be formed.\n\n# Complexity\n- **Time Complexity**: \n - $$O(m)$$ where $$m$$ is the length of the input array `nums`.\n - The loop runs as long as `missingNumber` is less than or equal to `n`, but in each iteration, either `missingNumber` is doubled, or an element from `nums` is used. Hence, the while loop will run at most `m + log(n)` times.\n\n- **Space Complexity**:\n - $$O(1)$$ as we only use a few extra variables (`missingNumber`, `patchesCount`, and `index`) regardless of the input size.\n\n# Swift Code\n```swift []\nclass Solution {\n func minPatches(_ nums: [Int], _ n: Int) -> Int {\n var missingNumber: Int = 1 // The smallest number that cannot be formed\n var patchesCount: Int = 0 // Number of patches (numbers) added\n var index: Int = 0 // Index to iterate through the nums array\n \n // While the missing number is less than or equal to n\n while missingNumber <= n {\n // If the current number in nums can be used to form the missing number\n if index < nums.count && nums[index] <= missingNumber {\n // Use nums[index] to cover the missing number and increment the index\n missingNumber += nums[index]\n index += 1\n } else {\n // Add the missing number itself to the range to cover the gap\n missingNumber += missingNumber\n patchesCount += 1\n }\n }\n \n // Return the number of patches added\n return patchesCount\n }\n}\n```
| 2 | 0 |
['Array', 'Greedy', 'Swift']
| 0 |
patching-array
|
Simple Greedy | TypeScript & JavaScript | Beats 100%
|
simple-greedy-typescript-javascript-beat-p4xo
|
Intuition\nThe goal is to determine the minimum number of patches needed to ensure that the array can represent any number in the range [1, n] (inclusive). By g
|
deleted_user
|
NORMAL
|
2024-03-24T07:42:36.058146+00:00
|
2024-03-24T07:42:36.058176+00:00
| 131 | false |
# Intuition\nThe goal is to determine the minimum number of patches needed to ensure that the array can represent any number in the range **[1, n]** *(inclusive)*. By greedily selecting the smallest number possible to add to the array at each step, we aim to maximize the range covered by the array without unnecessarily increasing its size.\n\n---\n\n\n# Approach\n1. Initialize three variables: **additions** to keep track of the number of patches added, **i** as the index for the input array **nums**, and **sum** to track the cumulative sum covered by the current array.\n1. Iterate until the sum reaches or exceeds **n**:\n - If the current element in **nums** can be added to the sum (i.e., **nums[i] <= sum + 1**), add it and move to the next element in **nums**.\n - Otherwise, add the next number (i.e., **sum + 1**) to the array to cover the gap and increment **additions**.\nReturn the total number of additions made.\n\n---\n\n\n# Complexity\n- Time complexity:\nThe time complexity of this approach is $O(log (n))$ in the worst case. This is because at each step, we either increment **i** or double **sum**, which results in at most *log\u2082(n)* iterations.\n\n- Space complexity:\nThe space complexity is $O(1)$ as we are using only a constant amount of extra space for storing variables regardless of the input size.\n\n# Code\n```TypeScript []\nfunction minPatches(nums: number[], n: number): number {\n let additions: number = 0, i: number = 0, sum: number = 0;\n\n while (sum < n) {\n if (i < nums.length && nums[i] <= sum + 1) {\n sum += nums[i], i++;\n }\n else {\n sum += sum + 1;\n additions++;\n }\n }\n return additions;\n};\n```\n```JavaScript []\nfunction minPatches(nums, n) {\n let additions = 0, i = 0, sum = 0;\n\n while (sum < n) {\n if (i < nums.length && nums[i] <= sum + 1) {\n sum += nums[i], i++;\n }\n else {\n sum += sum + 1;\n additions++;\n }\n }\n return additions;\n};\n```\n\n
| 2 | 0 |
['Greedy', 'TypeScript', 'JavaScript']
| 1 |
patching-array
|
c++ sol | Runtime 4ms | faster than 91.33%
|
c-sol-runtime-4ms-faster-than-9133-by-ut-81qy
|
Let\'s consider an example: \n\nLet\'s say the input is nums = [1, 2, 4, 13, 43] and n = 100. We need to ensure that all sums in the range [1,100] are possible.
|
UttamKumar22
|
NORMAL
|
2021-12-16T04:16:32.556814+00:00
|
2021-12-16T04:17:01.974040+00:00
| 177 | false |
**Let\'s consider an example: **\n\nLet\'s say the input is nums = [1, 2, 4, 13, 43] and n = 100. We need to ensure that all sums in the range [1,100] are possible.\nUsing the given numbers 1, 2 and 4, we can already build all sums from 0 to 7, i.e., the range [0,8). But we can\'t build the sum 8, and the next given number (13) is too large. So we insert 8 into the array. Then we can build all sums in [0,16).\n\nDo we need to insert 16 into the array? No! We can already build the sum 3, and adding the given 13 gives us sum 16. We can also add the 13 to the other sums, extending our range to [0,29).\n\nAnd so on. The given 43 is too large to help with sum 29, so we must insert 29 into our array. This extends our range to [0,58). But then the 43 becomes useful and expands our range to [0,101). At which point we\'re done.\n\n\n```\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n\t// To play safe from int overflow\n unsigned missing = 1, i = 0, ans = 0;\n\t\t// we will run this loop in the range of [1,n]\n while(missing <= n){\n\t\t// First check is to stay safe from runtime error\n\t// secondly we\'ll check if the each element of the array is smaller than or equals to the missing one\n\t\t// then we\'ll keep that element else we\'ll keep the twice of missing because of the concept I\'ve written above\n if(i < nums.size() && nums[i] <= missing){\n missing += nums[i];\n i++;\n }else{\n\t\t\t// if we got our nums[i] greater than the missing one then we can\'t keep it \n\t\t\t// so with this conclusion we can increase the count of our ans\n missing += missing;\n ans++;\n } \n }\n return ans;\n }\n};\n```
| 2 | 0 |
['C']
| 0 |
patching-array
|
Java with explanation
|
java-with-explanation-by-brucezu-jo2n
|
\n /*\n Idea:\n Watch the case [1,5,10], n = 20\n let r as the right side number value of continuous sum range [0, r]\n initial r=0; and expected n
|
brucezu
|
NORMAL
|
2021-09-14T02:06:50.136271+00:00
|
2021-09-14T02:06:50.136318+00:00
| 243 | false |
```\n /*\n Idea:\n Watch the case [1,5,10], n = 20\n let r as the right side number value of continuous sum range [0, r]\n initial r=0; and expected next number nums[i] should be <= r+1, else need a patch = r+1;\n if nums[i]==r+1 then r will be r+(r+1)\n if nums[i]< r+1 then r will be r+nums[i];\n i=0 numb[0] is 1, so need not patch and r=r+1= 1;\n i=1,numb[1] is 5, not expected <=2\n so need a patch =2;\n with the patch, now r=r+2=3 and expected <=4, but numb[1] is 5\n so need a patch =4;\n with the patch, now r=r+4=7 and expected <=8, numb[1] is 5 works now\n so now r=r+5=12, expected <=13, move i to next\n i=2,numb[2] is 10, need not patch\n r=r+10=22> target 20 then break the loop.\n\n Note \' 1 <= n <= 2^31 - 1\'\n so the `r` of continuous sum range [0, r] should be a long type\n\n Observe\n - we must patch the expected number else continuous sum range [0, r] can not continue\n\n\n O(m+logN) time, M is the length of nums. N is the give number n;\n O(1) space\n */\n public static int minPatches(int[] nums, int n) {\n int patches = 0, N = nums.length;\n long r = 0; // need use long to avoid overflow\n int i = 0;\n while (r < n) {\n if (i < N && nums[i] > r + 1 || i == N) {\n patches++; // patch = r+1\n r = 2 * r + 1;\n } else {\n r = r + nums[i];\n i++;\n }\n }\n return patches;\n }\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
Very Easy C++ Code (Explained)
|
very-easy-c-code-explained-by-jontystanl-gzt4
|
\tSteps:\n Please upvote if you find it helpful .\n\tEvery Interation we can have either of the three conditions:\n\tWe keep interating unitll our reach>=n\n\
|
jontystanley21
|
NORMAL
|
2021-08-30T06:58:26.056383+00:00
|
2021-08-30T07:01:59.503840+00:00
| 187 | false |
# \tSteps:\n Please upvote if you find it helpful .\n\tEvery Interation we can have either of the three conditions:\n\tWe keep interating unitll our **reach>=n**\n\t\n\t1. If my current number is less than or equal to reach, then add that to the reach and move i forward.\n\t2. If my current element, nums[i] is greater than the current reach then we search for the smallest number we should add to make the current element in reach, which is going to be (reach+1).\n\t3. If we surpass the array boundary i.e. i>nums.size(), we are again going to look for the smallest element we can add to reach the desired target n. This smallest number is going to be again (reach+1).\n```\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n int count=0;\n long long reach=0;\n int i=0;\n while(reach<n){\n if(i>=nums.size()){\n reach+=reach+1;\n count++;\n }\n else if(i<nums.size() && nums[i]<=reach+1){\n reach+=nums[i];\n i++;\n }\n else {\n reach+=reach+1;\n count++;\n }\n }\n return count;\n }\n};\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
simple java solution
|
simple-java-solution-by-manishkumarsah-luy5
|
\nclass Solution {\n public int minPatches(int[] nums, int n) {\n int count = 0;\n int i = 0;\n long reach = 0;\n \n while
|
manishkumarsah
|
NORMAL
|
2021-08-29T14:42:46.413643+00:00
|
2021-08-29T14:42:46.413698+00:00
| 114 | false |
```\nclass Solution {\n public int minPatches(int[] nums, int n) {\n int count = 0;\n int i = 0;\n long reach = 0;\n \n while(reach<n){\n \n if(i>=nums.length){\n reach += reach + 1;\n count++;\n }\n \n else if(i<nums.length && nums[i] <= (reach+1)){\n reach += nums[i];\n i++;\n }\n else{\n reach += reach + 1;\n count++;\n }\n \n }\n return count;\n }\n}\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
Python easy to understand solution
|
python-easy-to-understand-solution-by-so-noff
|
```\n def minPatches(self, nums: List[int], n: int) -> int:\n prevNum=0\n patches=0\n i=0\n while i=n): return patches\n
|
sourabhgome
|
NORMAL
|
2021-08-29T08:40:47.948455+00:00
|
2021-08-29T10:02:39.728032+00:00
| 99 | false |
```\n def minPatches(self, nums: List[int], n: int) -> int:\n prevNum=0\n patches=0\n i=0\n while i<len(nums):\n num=nums[i]\n if(prevNum>=n): return patches\n if(num<=prevNum+1):\n prevNum=prevNum+num\n i+=1\n else:\n patches+=1\n prevNum=prevNum+prevNum+1\n if(prevNum<n):\n while prevNum<n:\n patches+=1\n prevNum+=prevNum+1\n return patches
| 2 | 1 |
[]
| 0 |
patching-array
|
[Python3] greedy
|
python3-greedy-by-ye15-awvo
|
\n\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ans = prefix = k = 0 \n while prefix < n: \n if k < le
|
ye15
|
NORMAL
|
2021-05-07T22:42:28.006153+00:00
|
2021-05-07T22:42:28.006197+00:00
| 248 | false |
\n```\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n ans = prefix = k = 0 \n while prefix < n: \n if k < len(nums) and nums[k] <= prefix + 1: \n prefix += nums[k]\n k += 1\n else: \n ans += 1\n prefix += prefix + 1\n return ans \n```
| 2 | 0 |
['Python3']
| 2 |
patching-array
|
Java Greedy 100% Faster
|
java-greedy-100-faster-by-sunnydhotre-qb2h
|
```\n\tpublic int minPatches(int[] nums, int n) {\n int patches= 0;\n long sum= 0, limit= (long)n;\n for(int i=0; i=limit) break;\n
|
sunnydhotre
|
NORMAL
|
2021-04-03T09:30:44.407155+00:00
|
2021-04-03T09:48:09.546123+00:00
| 153 | false |
```\n\tpublic int minPatches(int[] nums, int n) {\n int patches= 0;\n long sum= 0, limit= (long)n;\n for(int i=0; i<nums.length; i++){\n if(sum>=limit) break;\n if(sum+1<nums[i]){\n i--; patches++;\n sum+= sum+1;\n }else sum+= (long)nums[i];\n }\n while(sum<limit){\n sum+= sum+1; patches++;\n }\n return patches;\n }
| 2 | 0 |
[]
| 0 |
patching-array
|
Simple C++ solution
|
simple-c-solution-by-caspar-chen-hku-fa8t
|
\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n long long maxReach = 0;\n int ans = 0;\n for(int i = 0; maxRe
|
caspar-chen-hku
|
NORMAL
|
2020-05-25T15:00:26.139923+00:00
|
2020-05-25T15:00:26.139975+00:00
| 176 | false |
```\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n long long maxReach = 0;\n int ans = 0;\n for(int i = 0; maxReach < n;) {\n if(i < nums.size() && nums[i] <= (maxReach + 1)) {\n maxReach = maxReach + nums[i];\n i++;\n } else {\n maxReach = maxReach + maxReach + 1;\n ans++;\n }\n }\n return ans;\n }\n};\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
Short C# Solution
|
short-c-solution-by-maxpushkarev-y28o
|
\n public class Solution\n {\n public int MinPatches(int[] nums, int n)\n {\n checked\n {\n (long from,
|
maxpushkarev
|
NORMAL
|
2020-03-29T05:13:06.415714+00:00
|
2020-03-29T05:13:06.415760+00:00
| 149 | false |
```\n public class Solution\n {\n public int MinPatches(int[] nums, int n)\n {\n checked\n {\n (long from, long to) range = (1, 1);\n int res = 0;\n int idx = 0;\n\n while (n >= range.to)\n {\n if (idx < nums.Length && nums[idx] <= range.to)\n {\n range = (range.from, range.to + nums[idx]);\n idx++;\n }\n else\n {\n res++;\n range = (range.from, 2 * range.to);\n }\n }\n\n return res;\n }\n }\n }\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
Complete Insightful Explanation | Recursive and Iterative Solutions
|
complete-insightful-explanation-recursiv-goks
|
Ignore the provided numbers array for a minute and just consider this:\nIf you wanted to use a numbering system that allowed you to make ANY sum, which numbers
|
chrisrocco
|
NORMAL
|
2019-08-05T19:07:47.882936+00:00
|
2019-08-05T19:07:47.882970+00:00
| 211 | false |
#### Ignore the provided numbers array for a minute and just consider this:\nIf you wanted to use a numbering system that allowed you to make ANY sum, which numbers would you use?\nWe could just use a sequence of ones [1,1,1,1,..,1], but we would need a LOT of them to make big sums (N of them to make all sums up to N).\n\nWe already know a numbering system that does this well: **binary**.\nWIth each binary digit we have, the largest sum, x, we can make increases by 2x + 1.\nFor example, if we have 4 digits, the largest sum we can make in binary is 2^n - 1 = 15 and it looks like: 1111.\nThe more significant the position, the more the digit is worth:\n* The 0th is worth 2^0 = 1\n* The 1st is worth 2^1 = 2\n* The 2nd is worth 2^2 = 4\n* ..And so on.\n\nIf we showed their values in base 10 in an array, it would look like this: [1, 2, 4, 8, 16, 32, ..., 2^n]\nIn fact, it is this array that is the smallest amount of numbers needed to make any sum!\nIf you understand binary, it should be intuitive why.\n\n#### How can we use this to find a solution?\nIf we want to increase the range of sums we can make, the best we can do is to add double the previous number.\nAnything larger would mean there is a sum that can\'t be made.\nFor example, if we had [1,2,4,9], we could make 7, but not 8, because 9 is larger than 4 * 2.\n\nHowever, we **can** use a number smaller than the previous, it just won\'t increase our range as much.\nWe are interested in minimizing the number of \'patches\' we make, and the numbers provided in the \'nums\' array come for free!\nWe can take advantage of this.\n\n#### OK - Let\'s see a full solution.\n\nWe will keep track of the largest possible sum we can make starting with 0 and incrementally extend it all the way to the target N.\nAt each step, we have two choices:\n* We can use a \'patch\' operation, in which case we would add the value "previous + 1". (Because this is largest we can extend the sum)\n* We can use the number provided in the nums array, which only extends it by the num\'s value, but it comes for free.\n\nAny time we CAN use the number provided, we should! This greedy approach yields an optimal solution.\nBut when CAN\'T we use the provided number? When it\'s **larger** than previous + 1!\n\nThat brings us full circle to a solution we can implement.\nI hope this was useful!\n\n#### Below are iterative and recursive implementations (in JS) for the described solution:\n\n**Recursive:**\n```js\n/**\n* @param tgt - The target sum.\n* @param cnt - Counts the number of patch operations so far.\n* @param S - Tracks the largest sum we can currently reach.\n* @param nums - The array of provided numbers\n*/\nlet solve = (tgt, cnt, S, [head, ...tail]) => {\n // Base Case -> We can now reach the target sum\n if (S >= tgt) return cnt\n \n // We\'re out of provided numbers -> Patch the largest reachable num (previous + 1).\n if (!head) return solve(tgt, cnt + 1, S + S + 1, [])\n \n // We CAN reach the next number -> Extend the range by that amount.\n if (head <= S + 1) return solve(tgt, cnt, S + head, tail)\n\n // Can\'t reach the next number -> Patch the largest reachable num.\n return solve(tgt, cnt + 1, S + S + 1, [head, ...tail])\n}\n\nlet minPatches = (nums, n) => solve(n, 0, 0, nums)\n```\n\n**Iterative:**\n```js\nvar minPatches = function(nums, n) {\n // Counts the number of patch operations.\n let operations = 0\n \n // Tracks the index in the nums array we are at. Moves left to right.\n let idx = 0\n \n // Tracks highest sum we can make using numbers below \'idx\' and with \'operations\'.\n let upper = 0\n \n // Keeping going until we can reach the target sum, n.\n while (upper < n) {\n \n if (idx < nums.length && nums[idx] <= upper + 1) {\n // If we can reach the next num, use it and extend the range (upper) by that amount.\n upper += nums[idx++]\n } else {\n // We can\'t reach the next num, so we need to patch.\n // For the patch, we want to extend the range as far as possible.\n // That is, upper + 1\n operations += 1\n upper += upper + 1\n }\n }\n return operations\n};\n```
| 2 | 0 |
[]
| 0 |
patching-array
|
C++ solution with detailed comments.
|
c-solution-with-detailed-comments-by-gal-lrkr
|
\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n long long maxReach = 0;\n int patch = 0;\n int S = nums.size(
|
galster
|
NORMAL
|
2018-10-29T03:48:35.527757+00:00
|
2018-10-29T03:48:35.527801+00:00
| 367 | false |
```\nclass Solution {\npublic:\n int minPatches(vector<int>& nums, int n) {\n long long maxReach = 0;\n int patch = 0;\n int S = nums.size();\n \n // traverse the array while maintaining the maxRead - the furthest number we can generate/\n // from the given numbers\n for(int i = 0; maxReach < n;){\n \n // if the next number is already covered by the range [1.. maxReach]\n // or it is just one passed maxReach we can add it to our total sum \n // to create a new maxReach range. \n if(i < S && nums[i] <= maxReach + 1){\n maxReach += (long long)nums[i];\n i++;\n }else{\n // if the next number is passed maxReach + 1 (or we have exhausted our array)\n // we should add a new number to our range (e.g. patch) and then this new number \n // effecitvely increases our ranges. By how much? we just need to add it to our range\n // to get a new range (which means that it doubles our range + 1)\n patch++;\n maxReach = maxReach*2 + 1;\n }\n }\n\t\t\t\t\n return patch;\n }\n};\n```
| 2 | 0 |
[]
| 2 |
patching-array
|
Actually patching
|
actually-patching-by-stefanpochmann-r0vh
|
int minPatches(vector<int>& nums, int n) {\n int k = nums.size();\n for (long miss=1, i=0; miss<=n; miss+=nums[i++])\n if (i == nums.si
|
stefanpochmann
|
NORMAL
|
2016-01-27T14:37:04+00:00
|
2016-01-27T14:37:04+00:00
| 918 | false |
int minPatches(vector<int>& nums, int n) {\n int k = nums.size();\n for (long miss=1, i=0; miss<=n; miss+=nums[i++])\n if (i == nums.size() || nums[i] > miss)\n nums.insert(nums.begin()+i, miss);\n return nums.size() - k;\n }\n\nO(k\xb7log(n)) instead of O(k+log(n)), but not too bad.
| 2 | 1 |
[]
| 0 |
patching-array
|
O(k+log(N)) time O(1) space java with explanation
|
oklogn-time-o1-space-java-with-explanati-6zo9
|
Iterating the nums[], while keep adding them up, and we are getting a running sum starting from 0. At any position i, if nums[i] > sum+1, them we are sure we ha
|
chipmonk
|
NORMAL
|
2016-01-27T05:27:14+00:00
|
2016-01-27T05:27:14+00:00
| 978 | false |
Iterating the nums[], while keep adding them up, and we are getting a running sum starting from 0. At any position i, if nums[i] > sum+1, them we are sure we have to patch a (sum+1) because all nums before index i can't make sum+1 even adding all of them up, and all nums after index i are all simply too large. Since the sum is growing from 0, we also can be sure that any number equal or smaller than the current sum is covered.\n\nIn the worst case, the code will go thru all the numbers in the array before the sum goes doubling itself towards n. Therefore, the time is O(k+log(n)) where k being the size of the array and n being the target n to sum up. Thanks @StefanPochmann for pointing it out.\n\nHere is the accepted code,\n\n public class Solution {\n public int minPatches(int[] nums, int n) {\n long sum = 0;\n int count = 0;\n for (int x : nums) {\n if (sum >= n) break;\n while (sum+1 < x && sum < n) { \n ++count;\n sum += sum+1;\n }\n sum += x;\n }\n while (sum < n) {\n sum += sum+1;\n ++count;\n }\n return count;\n }\n }
| 2 | 0 |
['Array', 'Java']
| 3 |
patching-array
|
Why long data type makes a difference
|
why-long-data-type-makes-a-difference-by-obkz
|
I tried write my own version of the code after understanding this fancy algorithm, however, i find that declare the variable with 'long' instead of 'int' really
|
zwsjink
|
NORMAL
|
2016-01-28T01:29:29+00:00
|
2016-01-28T01:29:29+00:00
| 770 | false |
I tried write my own version of the code after understanding this fancy algorithm, however, i find that declare the variable with 'long' instead of 'int' really make a difference:\n\n class Solution {\n public:\n int minPatches(vector<int>& nums, int n) {\n int miss_least = 1, i=0, cnt= 0;\n int M=nums.size();\n \n while(miss_least <= n){\n if (i<M && nums[i] <= miss_least){\n miss_least += nums[i++];\n }\n else{\n miss_least+=miss_least; // [1, miss_least +miss_least) to maximize the boundary\n cnt++;\n }\n }\n \n return cnt;\n \n }\n };\n\nHere, I declare the miss_least as an integer, the online judge just got TLE, when I change it to 'long', the code get Accepted. Anyone knows the reason?
| 2 | 0 |
[]
| 3 |
patching-array
|
7 line JavaScript solution
|
7-line-javascript-solution-by-linfongi-z95z
|
function minPatches(nums, n) {\n \tfor (var sum = 0, idx = 0, added = 0; sum < n;) {\n \t\tadded += idx === nums.length || nums[idx] > sum + 1 ? 1 : 0;\n
|
linfongi
|
NORMAL
|
2016-01-31T20:17:58+00:00
|
2016-01-31T20:17:58+00:00
| 515 | false |
function minPatches(nums, n) {\n \tfor (var sum = 0, idx = 0, added = 0; sum < n;) {\n \t\tadded += idx === nums.length || nums[idx] > sum + 1 ? 1 : 0;\n \t\tsum += (nums[idx] || n) > sum + 1 ? sum + 1 : nums[idx++];\n \t}\n \treturn added;\n }
| 2 | 0 |
['JavaScript']
| 0 |
patching-array
|
Simple Python Solution
|
simple-python-solution-by-dimal97psn-x4y3
|
def minPatches(self, nums, n):\n ans, nsum = 0, 0\n nums.append(n+1)\n for i in nums:\n num = min(i,n+1)\n while nsum
|
dimal97psn
|
NORMAL
|
2016-02-01T16:26:04+00:00
|
2016-02-01T16:26:04+00:00
| 805 | false |
def minPatches(self, nums, n):\n ans, nsum = 0, 0\n nums.append(n+1)\n for i in nums:\n num = min(i,n+1)\n while nsum + 1 < num:\n nsum += nsum + 1\n ans += 1\n nsum += num\n return ans
| 2 | 0 |
['Python']
| 0 |
patching-array
|
Easy to Understand 1ms Java solution
|
easy-to-understand-1ms-java-solution-by-ox6wf
|
public int minPatches(int[] nums, int n) {\n if(n<1) return 0;\n int patch=0;//number of patches\n int covers=0;//the cover range of curren
|
tlj77
|
NORMAL
|
2016-01-29T02:41:49+00:00
|
2016-01-29T02:41:49+00:00
| 1,091 | false |
public int minPatches(int[] nums, int n) {\n if(n<1) return 0;\n int patch=0;//number of patches\n int covers=0;//the cover range of current array\n for(int i=0;i<nums.length;i++){\n if(covers>=n) return patch;\n while(nums[i]-covers>1){\n patch++; //patch the covers+1\n covers=covers*2+1;\n if(covers>=n) return patch;\n }\n if(nums[i]>Integer.MAX_VALUE-covers) return patch;\n covers=nums[i]+covers;\n }\n while(covers<n){\n patch++;\n if(covers>Integer.MAX_VALUE-covers) return patch;\n covers=covers*2+1;\n }\n return patch;\n }
| 2 | 0 |
[]
| 1 |
patching-array
|
Javascript solution
|
javascript-solution-by-coderoath-j3dc
|
var minPatches = function(nums, n) {\n var covered=1,count=0,i=0;\n //current covered range is [1,covered)\n while(covered<=n){\n
|
coderoath
|
NORMAL
|
2016-02-19T18:43:06+00:00
|
2016-02-19T18:43:06+00:00
| 485 | false |
var minPatches = function(nums, n) {\n var covered=1,count=0,i=0;\n //current covered range is [1,covered)\n while(covered<=n){\n if(i>=nums.length||covered<nums[i]){\n count++;\n covered+=covered;\n }else covered+=nums[i++];\n }\n return count;\n };
| 2 | 0 |
['JavaScript']
| 0 |
patching-array
|
C#
|
c-by-adchoudhary-qux4
|
Code
|
adchoudhary
|
NORMAL
|
2025-02-20T06:37:54.204870+00:00
|
2025-02-20T06:37:54.204870+00:00
| 7 | false |
# Code
```csharp []
public class Solution {
public int MinPatches(int[] nums, int n) {
long max = 0, numsAdded = 0;
foreach (var num in nums)
{
while (num > max + 1) // O(LogT)
{
max += max + 1; // add no which is 1 greater than last max number we can create till now
numsAdded++; // increament count as we just added a new number
if (n < max)
return (int)numsAdded;
}
max += num; // add num present in array to max to get next point till where we can create numbe
if (n < max) break;
}
while (n > max) // O(LogT)
{
max += max + 1;
numsAdded++;
}
return (int)numsAdded;
}
}
```
| 1 | 0 |
['C#']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
✅2 Method's ||Strings||🌟JAVA||🧑💻 BEGINNER FREINDLY||C++||Python
|
2-methods-stringsjava-beginner-freindlyc-94g9
|
Approach1: Brute Force1.Loop Until Two Digits: Use a loop to keep processing the string until its length is reduced to 2.
2.Calculate New Digits: For each pair
|
Varma5247
|
NORMAL
|
2025-02-23T04:49:12.431905+00:00
|
2025-03-03T14:15:57.192407+00:00
| 2,781 | false |
# Approach1: Brute Force
<!-- Describe your approach to solving the problem. -->
1.**Loop Until Two Digits:** Use a loop to keep processing the string until its length is reduced to ```2```.
2.**Calculate New Digits:** For each pair of consecutive digits, calculate the new digit as ```(firstDigit + secondDigit) % 10```.
3.**Build New String**:Construct a new string from the calculated digits.
4.**Check Final Digits:** Once the loop ends, check if the two remaining digits are the same.
____
# ⏳Complexity Analysis
- Time complexity:🕒 $$O(n)$$ in each iteration
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(n) $$for the new string being built.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
____
# 💻Code Implementation
```java []
class Solution {
public boolean hasSameDigits(String s) {
while (s.length() > 2) {
StringBuilder newbornString = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
int firstDigit = s.charAt(i) - '0'; // Convert char to int
int secondDigit = s.charAt(i + 1) - '0'; // Convert char to int
int newDigit = (firstDigit + secondDigit) % 10; // Calculate new digit
newbornString.append(newDigit); // Append new digit to the new string
}
s = newbornString.toString(); // Update s to the new string
}
// Check if the final two digits are the same
return s.charAt(0) == s.charAt(1);
}
}
```
```c++ []
class Solution {
public:
bool hasSameDigits(std::string s) {
while (s.length() > 2) {
std::string newbornString;
for (size_t i = 0; i < s.length() - 1; i++) {
int firstDigit = s[i] - '0'; // Convert char to int
int secondDigit = s[i + 1] - '0'; // Convert char to int
int newDigit = (firstDigit + secondDigit) % 10; // Calculate new digit
newbornString += std::to_string(newDigit); // Append new digit to the new string
}
s = newbornString; // Update s to the new string
}
// Check if the final two digits are the same
return s[0] == s[1];
}
};
```
```python []
class Solution(object):
def hasSameDigits(self, s):
while len(s) > 2:
newborn_string = ""
for i in range(len(s) - 1):
first_digit = int(s[i]) # Convert char to int
second_digit = int(s[i + 1]) # Convert char to int
new_digit = (first_digit + second_digit) % 10 # Calculate new digit
newborn_string += str(new_digit) # Append new digit to the new string
s = newborn_string # Update s to the new string
# Check if the final two digits are the same
return s[0] == s[1]
```
___
# Approach2:HashSet
1 . **Unique Digits Check:**
- We start by creating a ```HashSet``` to store unique digits from the input string ```s```.
- If the string only contains one unique digit, return ```true``` because all digits are the same.
2 . **Iterative Reduction:**
- If the string has more than one unique digit, we reduce the string by summing adjacent digits modulo 10 until the length of the string becomes 2 or fewer.
3 . **Final Check:**
- Once the string is reduced to 2 digits, check if both digits are the same.
- Return ```true``` if they are the same; otherwise, return
```false```.
___
# ⏳Complexity Analysis
- Time complexity:🕒 $$O(n²)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(n) $$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
___
### 💻Code Implementation
```java []
class Solution {
public boolean hasSameDigits(String s) {
HashSet<Character> uniqueDigits = new HashSet<>();
// Add all digits to the HashSet
for (int i = 0; i < s.length(); i++) {
uniqueDigits.add(s.charAt(i));
}
// If there's only one unique digit, return true
if (uniqueDigits.size() == 1) {
return true;
}
// Reduce the digits until we have two or fewer
while (s.length() > 2) {
StringBuilder newbornString = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
// Calculate new digit as the sum of adjacent digits modulo 10
int newDigit = (s.charAt(i) - '0' + s.charAt(i + 1) - '0') % 10;
newbornString.append(newDigit);
}
s = newbornString.toString(); // Update s to the new string
}
// Check if the final two digits are the same
return s.charAt(0) == s.charAt(1);
}
}
```
```c++ []
class Solution {
public:
bool hasSameDigits(std::string s) {
std::unordered_set<char> uniqueDigits;
// Add all digits to the unordered_set
for (int i = 0; i < s.length(); i++) {
uniqueDigits.insert(s[i]);
}
// If there's only one unique digit, return true
if (uniqueDigits.size() == 1) {
return true;
}
// Reduce the digits until we have two or fewer
while (s.length() > 2) {
std::string newbornString;
for (int i = 0; i < s.length() - 1; i++) {
// Calculate new digit as the sum of adjacent digits modulo 10
int newDigit = (s[i] - '0' + s[i + 1] - '0') % 10;
newbornString += std::to_string(newDigit);
}
s = newbornString; // Update s to the new string
}
// Check if the final two digits are the same
return s[0] == s[1];
}
};
```
```python []
class Solution(object):
def hasSameDigits(self, s):
unique_digits = set(s)
# If there's only one unique digit, return true
if len(unique_digits) == 1:
return True
# Reduce the digits until we have two or fewer
while len(s) > 2:
newborn_string = ""
for i in range(len(s) - 1):
# Calculate new digit as the sum of adjacent digits modulo 10
new_digit = (int(s[i]) + int(s[i + 1])) % 10
newborn_string += str(new_digit)
s = newborn_string # Update s to the new string
# Check if the final two digits are the same
return s[0] == s[1]
```
**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
**🔼 Please Upvote**
**🔼 Please Upvote**
**🔼 Please Upvote**

| 15 | 3 |
['Hash Table', 'String', 'Python', 'C++', 'Java']
| 6 |
check-if-digits-are-equal-in-string-after-operations-i
|
Java Solution || 6ms
|
java-solution-6ms-by-dsuryaprakash89-3zuw
|
Approach
Start with a string sb
simulate till the length of string is greater than 2
Start with empty string nextsb
get the 1st 2 characters
compute the modulo
|
dsuryaprakash89
|
NORMAL
|
2025-02-23T04:30:11.814696+00:00
|
2025-02-23T04:30:11.814696+00:00
| 894 | false |
# Approach
- Start with a string sb
- simulate till the length of string is greater than 2
- Start with empty string nextsb
- get the 1st 2 characters
- compute the modulo
- append to nextsb
- this nextsb is now the string sb
- Return true if char at index 0 is equal to char at index 1
- else return false
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:$$ O(n^2)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() > 2) {
StringBuilder nextSb = new StringBuilder();
for (int i = 0; i < sb.length() - 1; i++) {
int a = sb.charAt(i) - '0';
int b = sb.charAt(i + 1) - '0';
nextSb.append((char)('0' + (a + b) % 10));
}
sb = nextSb;
}
return sb.charAt(0) == sb.charAt(1);
}
}
```
| 5 | 0 |
['String', 'Java']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
Python Elegant & Short | Simulation
|
python-elegant-short-simulation-by-kyryl-t6lt
|
Complexity
Time complexity: O(n2)
Space complexity: O(n)
Code
|
Kyrylo-Ktl
|
NORMAL
|
2025-03-06T08:24:01.164552+00:00
|
2025-03-06T08:24:01.164552+00:00
| 558 | false |
# Complexity
- Time complexity: $$O(n^2)$$
- Space complexity: $$O(n)$$
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
digits = [int(d) for d in s]
while len(digits) > 2:
digits = [(a + b) % 10 for a, b in pairwise(digits)]
one, two = digits
return one == two
```
| 4 | 0 |
['String', 'Simulation', 'Python', 'Python3']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
Two Lines Only
|
two-lines-only-by-charnavoki-unr8
| null |
charnavoki
|
NORMAL
|
2025-02-23T11:03:35.248294+00:00
|
2025-02-23T11:03:35.248294+00:00
| 334 | false |
```javascript []
const perform = ([a, ...b]) => b.map((x) => ([a, x] = [x, a], (+x + +a) % 10));
const hasSameDigits = f = s => s.length < 3 ? s[0] === s[1] : f(perform(s));
```
| 4 | 0 |
['JavaScript']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
simple solutions
|
simple-solutions-by-vinay_kumar_swami-ktl6
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
vinay_kumar_swami
|
NORMAL
|
2025-02-23T04:04:07.875057+00:00
|
2025-02-23T04:04:07.875057+00:00
| 1,076 | 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:
bool hasSameDigits(string s) {
while (s.size() > 2) {
string k = "";
for (int i = 0; i < s.size() - 1; i++) {
int sum = (s[i] - '0' + s[i + 1] - '0') % 10;
k += to_string(sum);
}
s = k;
}
return s[0] == s[1];
}
};
```
| 4 | 0 |
['C++']
| 2 |
check-if-digits-are-equal-in-string-after-operations-i
|
🌟 Simplest Solution Python3 💯🔥🗿
|
simplest-solution-python3-by-emmanuel011-ohdc
|
Code
|
emmanuel011
|
NORMAL
|
2025-02-25T20:23:20.366559+00:00
|
2025-02-25T20:23:20.366559+00:00
| 535 | false |
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
my_list = list(map(lambda x: int(x), s))
for _ in range(len(s) - 2):
my_list = [(my_list[i] + my_list[i + 1]) % 10 for i in range(len(my_list) - 1)]
return my_list[0] == my_list[1]
```
| 3 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
🔥 100% Beast Mode Activated! 🚀 Ultra-Efficient Java Solution
|
100-beast-mode-activated-ultra-efficient-ecz9
|
IntuitionImagine you are manually performing this task with a pen and paper. How would you do it?1️⃣ Look at the first two digits → Add them and write down only
|
Apoorv_jain24
|
NORMAL
|
2025-02-23T05:23:16.743642+00:00
|
2025-02-23T05:23:16.743642+00:00
| 94 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Imagine you are manually performing this task with a pen and paper. How would you do it?
1️⃣ Look at the first two digits → Add them and write down only the last digit (ignore carry).
2️⃣ Move to the next pair → Repeat the addition and record only the last digit.
3️⃣ Repeat until only two digits remain → Check if they are the same.
This feels like a shrinking sequence, where we repeatedly compress information step by step until we reach a final, condensed result.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Convert the string into an integer array.
2. Iterate while n > 2 and repeatedly transform the array:
3. Compute (digits[i] + digits[i+1]) % 10 for each pair.
4. Store the new values in place.
5. Reduce n after each pass.
6. Return true if the last two digits are equal, otherwise false.
# Complexity
- Time complexity: O(n²)
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n = s.length();
int[] digits = new int[n];
// can also be done using string builder
// Convert the string to an integer array
for (int i = 0; i < n; i++) {
digits[i] = s.charAt(i) - '0';
}
// Process the array until only two elements remain
while (n > 2) {
for (int i = 0; i < n - 1; i++) {
digits[i] = (digits[i] + digits[i + 1]) % 10;
}
// Reduce effective array size
n--;
}
return digits[0] == digits[1];
}
}
```
| 3 | 0 |
['Java']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
✅ ⟣ Java Solution ⟢
|
java-solution-by-harsh__005-s077
|
Code
|
Harsh__005
|
NORMAL
|
2025-02-23T04:02:53.607487+00:00
|
2025-02-23T04:02:53.607487+00:00
| 321 | false |
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n = s.length();
while(n > 2) {
String nstr = "";
for(int i=1; i<n; i++) {
int next = ((s.charAt(i)-'0')+(s.charAt(i-1)-'0')) % 10;
nstr += next;
}
n--;
s = nstr;
}
return s.charAt(0) == s.charAt(1);
}
}
```
| 3 | 1 |
['Java']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
✅ Check If Digits Are Equal || C++ ⚡ JAVA || Beginner Friendly 🔥🔥
|
check-if-digits-are-equal-c-java-beginne-z330
|
IntuitionThe problem involves iteratively transforming a string of digits by replacing each pair of adjacent digits with their sum modulo 10. This process conti
|
Devraj_Shirsath_18
|
NORMAL
|
2025-02-23T04:01:34.688829+00:00
|
2025-02-23T04:17:45.477973+00:00
| 527 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem involves iteratively transforming a string of digits by replacing each pair of adjacent digits with their sum modulo 10. This process continues until the string is reduced to two characters, at which point we check if they are the same. The intuition is to simulate this transformation step by step using a loop.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Start with the given string s.
2. While the length of s is greater than 2:
- Create a new string by iterating through adjacent character pairs.
- Compute their sum modulo 10 and store the result in a new string.
- Replace s with the newly generated string.
3. Once s is reduced to two characters, check if they are equal.
4. Return true if they match, otherwise return false.
# Complexity
**- Time complexity:**
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Each transformation reduces the string length approximately by half, leading to a logarithmic behavior.
- However, since we process all characters in each iteration, the worst case is O(n²).
**- Space complexity:**
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
- We store intermediate strings in each step, leading to O(n) auxiliary space.
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (s.length() > 2) {
string s1 = "";
for (size_t i = 0; i < s.length() - 1; i++) {
int a = (s[i] + s[i + 1] ) % 10;
s1 += a ;
}
s =s1;
}
return s[0] == s[1];
}
};
```
```java []
boolean hasSameDigits(String s) {
while (s.length() > 2) {
StringBuilder s1 = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
int a = (s.charAt(i) + s.charAt(i + 1)) % 10;
s1.append(a);
}
s = s1.toString();
}
return s.charAt(0) == s.charAt(1);
}
| 3 | 0 |
['String', 'C++', 'Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Trading Space for Speed 🚀 – Even Beginners Can Understand! | Python 3
|
trading-space-for-speed-even-beginners-c-ayji
|
Convert string to listCode
|
thiyophin22
|
NORMAL
|
2025-02-25T19:30:34.763619+00:00
|
2025-02-25T19:30:34.763619+00:00
| 349 | false |
Convert string to list
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
s = list(s)
temp = s
while len(s) != 2:
size = len(s)
s = []
for x in range(size-1):
s.append(str(int(int(temp[x]) + int(temp[x+1])) % 10))
temp = s
return s[0] == s[1]
```
| 2 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
005. done!
|
005-done-by-ritikaslaptop-p5cm
|
Intuitionsimple while loop⭐python allows returning boolean expressions directly instead of specifying !i.e this is unnecessary ⬇️Code
|
ritikaslaptop
|
NORMAL
|
2025-02-24T10:40:07.538949+00:00
|
2025-02-24T10:40:07.538949+00:00
| 185 | false |
# Intuition
simple while loop
⭐python allows returning boolean expressions directly instead of specifying !
i.e this is unnecessary ⬇️
```
if s[0] == s[1]:
return True
else:
return False
```
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
new_s = []
for i in range(len(s) - 1):
new_digit = (int(s[i]) + int(s[i + 1])) % 10
new_s.append(str(new_digit))
s = ''.join(new_s)
return s[0] == s[1]
```
| 2 | 0 |
['Python3']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
Iterative Modulo Reduction for Equal Digits Check
|
iterative-modulo-reduction-for-equal-dig-5ics
|
IntuitionThe problem requires repeatedly applying an operation to a string of digits until only two digits remain. The operation involves replacing each pair of
|
x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h
|
NORMAL
|
2025-02-23T18:26:34.056768+00:00
|
2025-02-23T18:26:34.056768+00:00
| 123 | false |
# Intuition
The problem requires repeatedly applying an operation to a string of digits until only two digits remain. The operation involves replacing each pair of consecutive digits with their sum modulo 10. The goal is to determine if the final two digits are the same.
# Approach
1. Iterative Reduction: Continuously apply the operation to the string until its length is reduced to two. Each iteration processes consecutive pairs of digits, replacing them with their sum modulo 10.
2. Check Final Digits: Once the string has exactly two digits, check if both digits are identical.
# Complexity
- Time complexity: $$O(n²)$$, where n is the initial length of the string. Each operation reduces the string length by 1, and each operation processes O(k) elements where k decreases from n to 3.
- Space complexity: $$O(n)$$, as each operation generates a new string of length one less than the previous.
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (s.size()>2){
string k="";
for (int i=0;i<s.size()-1;i++){k+=((s[i]-'0'+s[i+1]-'0')%10+'0');}
s=k;
}
return s[0]==s[1];
}
};
```
| 2 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
3ms Runtime || BEATS 100% || C++
|
3ms-runtime-beats-100-c-by-kartik_7-p19g
|
IntuitionKeep adding adjacent digits and taking their last digit until we either find same adjacent digits or end up with a single digit.Approach
While string l
|
Kartik_7
|
NORMAL
|
2025-02-23T12:23:46.392129+00:00
|
2025-02-23T12:23:46.392129+00:00
| 57 | false |
# Intuition
Keep adding adjacent digits and taking their last digit until we either find same adjacent digits or end up with a single digit.
# Approach
1. While string length > 1:
- For length 2: check if both digits same
- Add adjacent digits, keep last digit only
- Form new string with these sums
- Repeat until no more reduction possible
Example
```
"12345" → "3579" → "826" → "08" → "8"
Return false (single digit left)
```
# Complexity
- Time complexity: O(n^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.size()>1){
if(s.size()==2){
if(s[0]==s[1]) return true;
}
string temp;
for(int i=0; i<s.size()-1; i++){
temp+=(s[i]-'0'+s[i+1]-'0')%10;
}
s=temp;
}
return false;
}
};
```
| 2 | 0 |
['Hash Table', 'String', 'C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
3461. Check If Digits Are Equal in String After Operations I
|
3461-check-if-digits-are-equal-in-string-pk4a
|
Code
|
PanditJI20
|
NORMAL
|
2025-02-23T06:01:52.881388+00:00
|
2025-02-23T06:01:52.881388+00:00
| 385 | false |
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
arr =[]
arr.append(s)
while len(arr[-1])!=2:
res = ''
for i in range(len(arr[-1])-1):
res += str((int(arr[-1][i]) + int(arr[-1][i+1]))%10)
arr.append(res)
return arr[-1][0]==arr[-1][1]
```
| 2 | 0 |
['Python', 'Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy Beginner friendly C++ || Beats 90% +
|
easy-beginner-friendly-c-beats-90-by-nik-g6o5
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Nikhilk18
|
NORMAL
|
2025-02-23T04:46:35.375126+00:00
|
2025-02-23T04:46:35.375126+00:00
| 111 | 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:
bool hasSameDigits(string s) {
string t = s;
while(t.size() > 2){
string ans = "";
for(int i = 0; i<t.size()-1; i++){
int n1 = t[i] - '0';
int n2 = t[i+1] - '0';
int res = (n1 + n2) % 10;
ans.push_back(res + '0');
}
t = ans;
}
return t[0] == t[1];
}
};
```
| 2 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
🔢✨✅ Check If Digits Become Equal After Operations 🔁 | C++ 🧮 | Brute Force Approach 💪
|
check-if-digits-become-equal-after-opera-qg5x
|
🧠 Intuition
The goal is to check whether a given string of digits can be reduced to a 2-digit string where both digits are the same. At each step, you generate
|
manishkumar92913
|
NORMAL
|
2025-02-23T04:41:54.921066+00:00
|
2025-02-23T04:41:54.921066+00:00
| 57 | false |
# 🧠 Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- The goal is to check whether a given string of digits can be reduced to a 2-digit string where both digits are the same. At each step, you generate a new string by summing adjacent pairs of digits (mod 10) until the length of the string becomes 2.
# 📌 Approach
<!-- Describe your approach to solving the problem. -->
**1. Edge Case Check:**
- If the input string s already has a length of 2, we directly compare the two digits.
**2. Iterate Until Length is 2:**
- Create a new string by summing every pair of consecutive digits.
- Store the last digit of each sum using modulo 10.
- Update s with the new string.
**3. Final Check:**
- Return true if the two remaining digits are the same; otherwise, return false.
# ⏳ Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Each iteration reduces the string length by 1. Starting with length 𝑛, there are 𝑂(𝑛) iterations.
- Within each iteration, constructing the new string takes 𝑂(𝑛) time.
- Therefore, the overall complexity is 𝑂(𝑛^2).
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
- We use extra space for the new string in each iteration, which is proportional to the input size 𝑂(𝑛).
- Thus, the space complexity is 𝑂(𝑛).
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (s.length() > 2) {
string str = "";
for (int i = 0; i < s.length() - 1; i++) {
int sum = (s[i] - '0') + (s[i + 1] - '0');
str += to_string(sum % 10);
}
s = str;
}
return s[0] == s[1];
}
};
```
| 2 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
simplest solution | c++
|
simplest-solution-c-by-hriii11-vtfh
|
IntuitionThe problem involves repeatedly reducing a string by summing consecutive digits and taking only the last digit (mod 10). The process continues until th
|
Hriii11
|
NORMAL
|
2025-02-23T04:09:48.950048+00:00
|
2025-02-23T04:09:48.950048+00:00
| 31 | false |
# Intuition
The problem involves repeatedly reducing a string by summing consecutive digits and taking only the last digit (mod 10). The process continues until the string is reduced to two characters, at which point we check if they are equal.
# Approach
1. Start with a given numeric string s.
2. Continuously reduce the string:
3. Compute a new string where each character is the last digit of the sum of adjacent characters.
4. Repeat until only two characters remain.
5. Check if the two remaining characters are equal.
# Complexity
- Time complexity:
$$O(n^2)$$
- Space complexity:
$$O(n)$$
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.length()>2){
string temp;
for(int i=0; i<s.size()-1;i++){
int sum= (s[i]-'0')+(s[i+1]-'0');
temp+=(sum%10)-'0';
}
s=temp;
}
return(s[0]==s[1]);
}
};
```
| 2 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
🔢 Check if a Number String Reduces to Two Same Digits
|
check-if-a-number-string-reduces-to-two-4uwf9
|
✅ IntuitionThe problem requires checking whether a string of digits, through a series of transformations, reduces to two identical digits.
In each transformatio
|
solaimuthu
|
NORMAL
|
2025-03-31T20:33:33.240576+00:00
|
2025-03-31T20:33:33.240576+00:00
| 45 | false |
## ✅ **Intuition**
The problem requires checking whether a string of digits, through a series of transformations, reduces to two identical digits.
- In each transformation:
- For every adjacent pair of digits:
- Add them together.
- Append the last digit of the sum (using modulo 10) to form a new string.
- This process continues until the string contains only **two digits**.
- Finally, compare the two digits to see if they are the same.
---
## 🔥 **Approach**
1. **Iterate Until Length Reduces to 2:**
- Use a loop to repeatedly transform the string until it has only two digits.
2. **Form a New String in Each Iteration:**
- Use a `StringBuilder` to build the new string.
- Iterate through adjacent pairs of digits:
- Convert each character to an integer.
- Add the two adjacent digits.
- Append the last digit of the sum (`(firstDigit + secondDigit) % 10`) to the new string.
3. **Repeat the Process:**
- Update the string to the new transformed string.
- Continue the transformation process until the string length becomes **2**.
4. **Final Check:**
- Compare the two digits:
- If they are the same, return `true`.
- Otherwise, return `false`.
---
## ⏱️ **Complexity Analysis**
- **Time Complexity:**
- Each iteration reduces the string length by **1**, making the process $$O(n)$$, where `n` is the initial length of the string.
- Since the transformation continues until the string length becomes **2**, it takes approximately $$O(n)$$ steps.
- **Space Complexity:**
- $$O(n)$$ for the `StringBuilder` used to store the transformed string at each step.
---
## 🛠️ **Code**
```java
class Solution {
public boolean hasSameDigits(String s) {
while (s.length() > 2){
StringBuilder newString = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++){
int firstDigit = s.charAt(i) - '0'; // Convert char to int
int secondDigit = s.charAt(i + 1) - '0'; // Convert char to int
int newDigit = (firstDigit + secondDigit) % 10;
newString.append(newDigit);
}
s = newString.toString();
}
return s.charAt(0) == s.charAt(1);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Efficient Digit Compression and Comparison in Strings
|
efficient-digit-compression-and-comparis-xy01
|
🔥 IntuitionThe goal is to repeatedly reduce the string by summing adjacent digits and appending the result modulo 10 until the string length becomes 2 or less.
|
vishwajeetwalekar037
|
NORMAL
|
2025-03-25T07:14:56.551756+00:00
|
2025-03-25T07:14:56.551756+00:00
| 23 | false |
### 🔥 **Intuition**
<!-- Describe your first thoughts on how to solve this problem. -->
The goal is to repeatedly **reduce the string** by summing adjacent digits and appending the result modulo `10` until the string length becomes **2 or less**.
- If the resulting string has exactly **two equal digits**, return `true`.
- Otherwise, return `false`.
💡 **Key Insight:**
- The process mimics **digit compression**, where the string is progressively shortened by combining adjacent digits.
---
### 🚀 **Approach**
<!-- Describe your approach to solving the problem. -->
1. **Iteration Until Length ≤ 2:**
- Use a `while` loop that continues until the string length is **2 or less**.
2. **Combining Adjacent Digits:**
- Iterate over the string with a `for` loop.
- Extract adjacent digits using `charAt()` and convert them to integers using `Integer.parseInt()`.
- Sum the adjacent digits and take the result modulo `10`.
- Append the result to a `StringBuilder`.
3. **Update the String:**
- After each iteration, update the string (`s`) with the newly formed string (`sb.toString()`).
4. **Final Comparison:**
- When the length is reduced to **2**, check if the two digits are the same.
- Return `true` if they are equal, otherwise `false`.
---
### 🔥 **Complexity Analysis**
- **Time Complexity:**
\[O(n \log n)\]
- Each iteration reduces the string length roughly by **half**, making the process logarithmic.
- In each iteration, you process the entire string of length `n`, making it `O(n)` per iteration.
- Therefore, the overall complexity is **`O(n log n)`**.
- **Space Complexity:**
\[O(n)\]
- You create a `StringBuilder` during each iteration, which holds the compressed digits.
- In the worst case, the space complexity is proportional to the size of the input string, hence **`O(n)`**.
---
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
while (s.length() > 2) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < s.length(); i++) {
int num = (Integer.parseInt(Character.toString(s.charAt(i - 1))) + Integer.parseInt(Character.toString(s.charAt(i)))) % 10;
sb.append(Integer.toString(num));
}
s = sb.toString();
}
return s.charAt(0) == s.charAt(1);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Clean solution📈 || Brute force
|
clean-solution-brute-force-by-ashish-joh-yis7
|
Code
|
ashish-john
|
NORMAL
|
2025-03-22T07:13:43.250947+00:00
|
2025-03-22T07:13:43.250947+00:00
| 25 | false |
# Code
```javascript []
/**
* @param {string} s
* @return {boolean}
*/
var hasSameDigits = function(s) {
while (s.length > 2) {
let result = '';
for (let i = 0; i < s.length - 1; i++) {
let sum = (s[i] - '0') + (s[i + 1] - '0');
result += (sum % 10).toString();
}
s = result;
}
return s[0] === s[1];
};
```
| 1 | 0 |
['JavaScript']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
python3 solution beats 95.15%
|
python3-solution-beats-9515-by-nullx37-0b75
|
IntuitionPerform operations till we shrink the list's length to 2ApproachStack based approachComplexity
Time complexity:
Space complexity:
Code
|
nullx37
|
NORMAL
|
2025-03-19T05:32:32.113860+00:00
|
2025-03-19T05:32:32.113860+00:00
| 79 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Perform operations till we shrink the list's length to 2
# Approach
<!-- Describe your approach to solving the problem. -->
Stack based approach
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Close to O(N^2)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(N)
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
ls = list(s)
for i in range(0, len(ls)-1):
ls[i] = (int(ls[i]) + int(ls[i+1])) % 10
ls.pop()
while len(ls) != 2:
for i in range(0, len(ls)-1):
ls[i] = (ls[i] + ls[i+1]) % 10
ls.pop()
return ls[0] == ls[1]
```
| 1 | 0 |
['Array', 'Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Beats 100% Easy Java Code to Understand Line to Line Explanation
|
beats-100-easy-java-code-to-understand-l-7d2b
|
Code
|
adityaa_panwar
|
NORMAL
|
2025-03-02T03:38:50.372200+00:00
|
2025-03-02T03:38:50.372200+00:00
| 51 | false |
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n=s.length();
int[] digit=new int[n];
for(int i=0;i<n;i++){
digit[i]=s.charAt(i)-'0'; //it get the Digit Value as charAt(i)-'0 = '3'-'0' = 51-48 = 3
}
while(n>2){ //performs the operation until we get the 2 digit
for(int i=0;i<n-1;i++){
digit[i]=(digit[i]+digit[i+1])%10;//applying the given operation
}
n--;//reduce the array size
}
return digit[0]==digit[1];//return true or false according to the condition
}
}
```
| 1 | 0 |
['Math', 'String', 'String Matching', 'Number Theory', 'Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Weekly Contest 438 Q#1
|
weekly-contest-438-q1-by-xcwrebnifv-m0lz
|
IntuitionThe intuition behind this approach is straightforward—we can directly follow the given instructions to arrive at the optimal solution.Approach
Perform
|
xcwrEbNifv
|
NORMAL
|
2025-03-01T07:43:27.457528+00:00
|
2025-03-01T07:43:27.457528+00:00
| 69 | false |
# Intuition
The intuition behind this approach is straightforward—we can directly follow the given instructions to arrive at the optimal solution.
# Approach
1. Perform the given operations iteratively, updating all elements up to `lenth - 1`.
2. After each iteration, the effective length of the array decreases by one.
2. Repeat step #1 until only two characters remain.
# Complexity
- Time complexity:
* The overall time complexity of this solution is `Quadratic`
- Space complexity:
* The overall space complexity of this solution is `Constant`
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
char[] digits = s.toCharArray();
int length = digits.length;
while (length > 2) {
for (int i = 0; i < length - 1; i++) {
digits[i] = (char) ((digits[i] + digits[i + 1] - 96) % 10 + 48);
}
length--;
}
return digits[0] == digits[1];
}
}
```
| 1 | 0 |
['Java']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
🥇 Beat 100%
|
beat-100-by-nkoruts-2sty
|
Code
|
nkoruts
|
NORMAL
|
2025-02-26T23:21:17.192829+00:00
|
2025-02-26T23:21:17.192829+00:00
| 46 | false |
# Code
```swift []
class Solution {
func hasSameDigits(_ s: String) -> Bool {
var array = s.compactMap(\.wholeNumberValue)
while array.count > 2 {
for index in 1..<array.count {
array[index - 1] = (array[index - 1] + array[index]) % 10
}
array.removeLast()
}
return array.first == array.last
}
}
```
| 1 | 0 |
['Swift']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
EASY C++
|
easy-c-by-hnmali-9d18
|
Code
|
hnmali
|
NORMAL
|
2025-02-25T18:12:24.001734+00:00
|
2025-02-25T18:12:24.001734+00:00
| 45 | false |
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.size() > 2) {
for(int i = 0; i < s.size()-1; i++) {
int temp = s[i]+s[i+1]-'0'-'0';
temp %= 10;
s[i] = temp + '0';
}
s.pop_back();
}
return s[0] == s[1];
}
};
```
| 1 | 0 |
['Math', 'String', 'Simulation', 'C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Beats 56% | Python 3
|
beats-56-python-3-by-alpha2404-f1yv
|
Please UpvoteCode
|
Alpha2404
|
NORMAL
|
2025-02-25T03:36:42.278456+00:00
|
2025-02-25T03:36:42.278456+00:00
| 90 | false |
# Please Upvote
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
def operate(s):
temp = ""
for i in range(len(s)-1):
temp+=str((int(s[i])+int(s[i+1]))%10)
return temp
while len(s)!=2:
s = operate(s)
return s[0]==s[1]
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy In-place C++ Solution | No Extra Space/Memory Used | Beats 100% in Time and Space
|
easy-in-place-c-solution-no-extra-spacem-wa1q
|
IntuitionThe in-place modification works by overwriting each pair's left position with their sum modulo 10, while the inner loop processes pairs from left to ri
|
pratiiik_p
|
NORMAL
|
2025-02-24T18:43:16.971760+00:00
|
2025-02-26T14:17:13.178837+00:00
| 47 | false |
# Intuition
The in-place modification works by overwriting each pair's left position with their sum modulo 10, while the inner loop processes pairs from left to right. Since each step uses the original right digit (not yet overwritten in this iteration), it safely updates positions without affecting subsequent pairs in the same reduction step.
Here is a visualization for the sample input `s = "1234"` using text-based diagrams. Below is a structured representation of the in-place modification steps:
---
### **Sample Input**: `"1 2 3 4"`
**Goal**: Reduce to 2 digits via iterative in-place updates.
---
### **Iteration 1 (Reduce from 4 → 3 digits)**
**Original String**:
```
Indices: 0 1 2 3
Values: 1 2 3 4
```
**Process pairs left-to-right**:
1. **Pair (0,1)**: `(1+2)%10 = 3` → Update index **0**:
```
Values: 3 2 3 4
```
2. **Pair (1,2)**: `(2+3)%10 = 5` → Update index **1**:
```
Values: 3 5 3 4
```
3. **Pair (2,3)**: `(3+4)%10 = 7` → Update index **2**:
```
Values: 3 5 7 4
```
**Result after Iteration 1**: Use first 3 digits → `"3 5 7"`.
---
### **Iteration 2 (Reduce from 3 → 2 digits)**
**Current String**:
```
Indices: 0 1 2
Values: 3 5 7
```
**Process pairs left-to-right**:
1. **Pair (0,1)**: `(3+5)%10 = 8` → Update index **0**:
```
Values: 8 5 7
```
2. **Pair (1,2)**: `(5+7)%10 = 2` → Update index **1**:
```
Values: 8 2 7
```
**Final Result**: First 2 digits → `"8 2"` → **Not equal** → `false`.
# Approach
The approach used in the provided code involves simulating each step of the process iteratively until the string is reduced to exactly two digits. Here's a breakdown of the method:
1. **Iterative Reduction**: The code reduces the length of the string by one in each iteration of the outer loop. This is done by processing consecutive pairs of digits and replacing them with their sum modulo 10.
2. **In-Place Modification**: For each iteration, the string is modified in-place. Each pair of consecutive digits is processed from left to right, and the result is stored in the left position of the pair. This ensures that subsequent pairs in the same iteration use the original values of the right digits that haven't been overwritten yet.
3. **Outer Loop Control**: The outer loop runs exactly `n-2` times, where `n` is the initial length of the string. This ensures that after `n-2` reductions, the string is left with exactly two digits.
4. **Final Check**: After all iterations, the first two characters of the modified string are checked for equality to determine the result.
# Complexity
- Time complexity: O(n^2)
- Space complexity: O(1)
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
int n = s.size();
for(int j = 0; j<n-2; j++){
for(int i=1; i<n-j; i++){
int num = s[i] - '0', prev_num = s[i-1]-'0';
s[i-1] = ((num + prev_num)%10)+'0';
}
}
return s[0] == s[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Best and Easiest Approach to solve this question with 100% beats (GUARANTEED)
|
best-and-easiest-approach-to-solve-this-jtarr
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
HARDIK_ARORA_16
|
NORMAL
|
2025-02-24T17:07:04.521419+00:00
|
2025-02-24T17:07:04.521419+00:00
| 10 | 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
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
s1 = ""
for i in range(1 , len(s)):
s1 += str((int(s[i]) + int(s[i - 1])) % 10)
s = s1
if s[0] == s[1]:
return True
return False
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy Solution
|
easy-solution-by-kundankumar95-gi2l
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
kundankumar95
|
NORMAL
|
2025-02-24T17:06:30.719320+00:00
|
2025-02-24T17:06:30.719320+00:00
| 22 | 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:
bool hasSameDigits(string s) {
while(true){
string str = "";
for(int i=1;i<s.length();i++){
int num1 = s[i] - '0';
int num2 = s[i-1] - '0';
int sum = num1 + num2;
str += (sum%10 + '0');
}
if(str.length() == 2){
if(str[0] == str[1]){
return true;
}
else{
return false;
}
}
s = str;
}
return false;
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple Java Solution with Detail Explanation
|
simple-java-solution-with-detail-explana-ap0e
|
IntuitionThe problem requires checking whether a given string of digits can be reduced to two equal numbers by repeatedly summing adjacent digits modulo 10.The
|
tejassinkar24
|
NORMAL
|
2025-02-24T13:41:27.618811+00:00
|
2025-02-24T13:41:27.618811+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires checking whether a given string of digits can be reduced to two equal numbers by repeatedly summing adjacent digits modulo 10.
The key observation is that at each step, the array size decreases by 1, and the elements are updated using the sum of adjacent elements modulo 10. The process continues until only two elements remain, and we check if they are equal.
# Approach
<!-- Describe your approach to solving the problem. -->
Convert the input string s into an integer array temp, where each character is converted into its corresponding integer value (s.charAt(i) - '0').
Use a variable p initialized to the length of temp, representing the current size of the array.
While p > 2, iterate through the array and replace each element with the sum of itself and the next element, taken modulo 10.
Decrease p to indicate that the array has shrunk.
When only two elements remain, check if they are equal. If they are, return true; otherwise, return false.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
The outer loop runs until the array size reduces to 2, which happens in O(n) iterations.
The inner loop processes O(n), O(n-1), ..., O(2) elements over time, totaling O(n²) in the worst case.
Therefore, the overall time complexity is O(n²).
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
We use an extra integer array temp of size n, leading to a space complexity of O(n).
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
// Create an array to store integer values of the digits in the string
int[] temp = new int[s.length()];
// Convert each character in the string to its integer representation
for (int i = 0; i < temp.length; i++) {
temp[i] = s.charAt(i) - '0'; // Convert character to integer
}
// Store the current length of the array
int p = temp.length;
// Reduce the array size until only two elements remain
while (p > 2) {
// Iterate through the array and update each element
for (int i = 0; i < p - 1; i++) {
temp[i] = (temp[i] + temp[i + 1]) % 10; // Sum adjacent elements modulo 10
}
// Reduce the array size by one
p--;
}
// Check if the last two remaining elements are the same
return temp[0] == temp[1];
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
100% Affective CPP Solution
|
100-affective-cpp-solution-by-sanchit812-bbb7
|
IntuitionApproachComplexity
Time complexity:O(n^2)
Space complexity:O(1)
Code
|
Sanchit8125
|
NORMAL
|
2025-02-24T12:03:40.920522+00:00
|
2025-02-24T12:03:40.920522+00:00
| 33 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n^2)
- Space complexity:
O(1)
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
if(s.length()<3) return s[0]==s[1]?true:false;
while(true)
{
for(int i=0;i<s.length()-1;i++)
{
s[i]=(s[i]+s[i+1])%10;
}
s.pop_back();
if(s.length()==2) return s[0]==s[1]?true:false;
}
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy to understand , Beats 100 % both memory and time complexity
|
easy-to-understand-beats-100-both-memory-7zpe
|
IntuitionApproachComplexity
Time complexity:O(N)
Space complexity:O(N)
Code
|
SHIJITH7498
|
NORMAL
|
2025-02-24T07:29:40.205418+00:00
|
2025-02-24T07:29:40.205418+00:00
| 98 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
lists = list(s)
result = []
i = 0
while i < len(lists) - 1:
if len(lists) == 2:
if lists[0] == lists[1]:
return True
else:
return False
result.append((int(lists[i]) + int(lists[i + 1])) % 10)
if i == len(lists) - 2:
lists = result
result = []
i = 0
else:
i += 1
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple CPP Solution
|
simple-cpp-solution-by-deva766825_gupta-2lcp
|
Code
|
deva766825_gupta
|
NORMAL
|
2025-02-24T04:38:53.197800+00:00
|
2025-02-24T04:38:53.197800+00:00
| 7 | false |
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.length()>2)
{
string curr="";
for(int i=0;i<s.length()-1;i++){
int sum=(s[i]-'0'+s[i+1]-'0')%10;
curr+=(sum+'0');
}
s=curr;
}
return s[0]==s[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy Solution using QUEUE | C++
|
easy-solution-using-queue-c-by-rahmankha-t1a0
|
IntuitionThe idea is inspired by pairwise reduction, where at each step, two adjacent numbers are summed, and only the last digit (% 10) is considered.The proce
|
Rahmankhan3
|
NORMAL
|
2025-02-23T20:03:54.851057+00:00
|
2025-02-23T20:03:54.851057+00:00
| 27 | false |
# Intuition
The idea is inspired by pairwise reduction, where at each step, two adjacent numbers are summed, and only the last digit (% 10) is considered.
The process continues until only two digits remain.
Finally, we compare the last two digits to determine if they are the same.
# Approach
Initialize a queue: Convert the input string s into a queue, storing its digits as integers.
Iterative Reduction:
While the queue has more than two elements:
Process the queue by summing adjacent elements, taking (first + second) % 10, and pushing it to the queue.
After processing all elements for that iteration, remove the last element from the queue (since it has already contributed to the summation).
Final Check:
After the loop, two elements remain in the queue.
If both elements are equal, return true; otherwise, return false.
# Complexity
- Time complexity:
This forms a series O(n + (n-1) + (n-2) + ... + 3) ≈ O(n²).
- Space complexity:
The space complexity is O(n).
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
queue<int>st;
for(int i=0;i<s.size();i++){
st.push(s[i]-'0');
}
while(st.size()>2){
int n=st.size();
for(int i=0;i<n-1;i++){
int first=st.front();
st.pop();
int second=st.front();
st.push((first+second)%10);
}
st.pop();
}
int first=st.front();
st.pop();
int second=st.front();
if(first==second) return true;
return false;
}
};
```
| 1 | 0 |
['Queue', 'C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Best Solution 👌👇
|
best-solution-by-ram_saketh-2xrb
|
Complexity
Time complexity:O(n^2)
Space complexity:O(n)
Code
|
Ram_Saketh
|
NORMAL
|
2025-02-23T19:49:38.287074+00:00
|
2025-02-23T19:49:38.287074+00:00
| 11 | false |
# Complexity
- Time complexity:O(n^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
if (s.length() < 2) return true;
while(s.length() > 2){
String ans = "";
for(int i=0;i<s.length()-1;i++){
ans += String.valueOf((Integer.valueOf(s.charAt(i)) - '0' + Integer.valueOf(s.charAt(i + 1)) - '0') % 10);
}
s = ans ;
}
if (s.charAt(0) == s.charAt(1)) return true;
else return false;
}
}
```
| 1 | 0 |
['String', 'String Matching', 'Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
E
|
e-by-runningfalcon-c8vd
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
runningfalcon
|
NORMAL
|
2025-02-23T18:43:14.911628+00:00
|
2025-02-23T18:43:14.911628+00:00
| 12 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
char[] ss = s.toCharArray();
int n = s.length();
while (n > 2) {
char[] temp = new char[n - 1];
for (int i = 1; i < ss.length; i++) {
int x = (ss[i - 1] - '0') + (ss[i] - '0');
temp[i - 1] = (char) ((x % 10) + '0');
}
ss = temp;
n--;
}
return (ss.length == 2) && (ss[0] == ss[1]);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
AAAAAAAAAAAAAAAAAAAAAAAAAAA
|
aaaaaaaaaaaaaaaaaaaaaaaaaaa-by-danisdeve-imzh
|
Code
|
DanisDeveloper
|
NORMAL
|
2025-02-23T17:31:01.678725+00:00
|
2025-02-23T17:31:01.678725+00:00
| 15 | false |
# Code
```kotlin []
class Solution {
fun hasSameDigits(s: String): Boolean {
var current = s.toMutableList()
while (true) {
val temp = mutableListOf<Char>()
for (i in 0 until current.size - 1) {
val sum = (current[i].code + current[i + 1].code - '0'.code * 2) % 10
temp.add((sum + '0'.code).toChar())
}
if(temp.size == 2) return temp[0] == temp[1]
current = temp
}
return false;
}
}
```
| 1 | 0 |
['Kotlin']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
C++ [Easy] 🔥🎊
|
c-easy-by-varuntyagig-w9ua
|
Code
|
varuntyagig
|
NORMAL
|
2025-02-23T17:08:11.071483+00:00
|
2025-02-23T17:08:11.071483+00:00
| 26 | false |
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (true) {
string str = "";
for (int i = 0; i < s.length() - 1; ++i) {
str += (((s[i] + s[i + 1]) % 10) + '0');
}
if (str.length() == 2) {
if (str[0] == str[1]) {
return true;
} else if (str[0] != str[1]) {
return false;
}
} else if (str.length() > 2) {
s = str;
}
}
return 1;
}
};
```
| 1 | 0 |
['String', 'C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
it's work
|
its-work-by-bhav5sh-gc05
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Bhav5sh
|
NORMAL
|
2025-02-23T13:01:42.886426+00:00
|
2025-02-23T13:01:42.886426+00:00
| 61 | 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
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
new_s = ''
for i in range(len(s) - 1):
digit1 = ord(s[i]) - ord('0')
digit2 = ord(s[i + 1]) - ord('0')
ch = str((digit1 + digit2) % 10)
new_s += ch
s = new_s
return s[0] == s[1]
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
0ms 100% infinite harmony check
|
0ms-100-by-michelusa-fbd8
|
ApproachThe core idea revolves around iterative digit reduction. We start with a string of digits and repeatedly transform it by processing adjacent pairs.The c
|
michelusa
|
NORMAL
|
2025-02-23T11:42:18.944068+00:00
|
2025-02-23T12:03:55.780937+00:00
| 28 | false |
**Approach**
The core idea revolves around iterative digit reduction. We start with a string of digits and repeatedly transform it by processing adjacent pairs.
The code enters an infinite for (;;) loop, designed for repeated transformation until a termination condition is met:
- Adjacent Digit Summation
- Termination and Harmony Check
- String update/Swap
**Complexity**
In each iteration, the inner loop scales with the current string length, which decreases by approximately one in each outer iteration. Consequently, the time complexity is O(n<sup>2</sup>) where n is the initial string length.
The space usage is dominated by the temporary string next. Its size is, at most, the size of the input string in each iteration. Therefore, the space complexity remains O(n).
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string& s) {
constexpr int TWO_ASCII_ZERO = 2 * '0';
string next;
next.reserve(s.size());
for (;;) {
next.clear();
for (int i = 1; i < s.size(); ++i) {
const int sum = ( (s[i - 1] + s[i] - TWO_ASCII_ZERO ) ) ;
const int char_sum = ((sum <= 9) ? sum : (sum - 10)) + '0';
next.push_back(char_sum);
}
if (next.size() == 2) {
return next.front() == next.back();
}
swap(next, s);
}
return false;
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple java solution- O(log(n))
|
simple-java-solution-ologn-by-swapit-tl5p
|
Code
|
swapit
|
NORMAL
|
2025-02-23T08:32:26.336774+00:00
|
2025-02-23T08:32:26.336774+00:00
| 45 | false |
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
while (s.length()>2) {
String str = "";
for (int i = 0; i < s.length() - 1; i++) {
int num = Character.getNumericValue(s.charAt(i)) + Character.getNumericValue(s.charAt(i + 1));
str += num%10;
}
s = str;
}
return s.charAt(0) == s.charAt(1);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy and simple explanation in python 🚀🚀
|
easy-and-simple-explanation-in-python-by-vucv
|
IntuitionWe repeatedly replace each pair of adjacent digits with their sum modulo 10. This reduces the length of the string step by step until only two digits r
|
harshit197
|
NORMAL
|
2025-02-23T08:27:37.214833+00:00
|
2025-02-23T08:27:37.214833+00:00
| 27 | false |
# Intuition
We repeatedly replace each pair of adjacent digits with their sum modulo 10. This reduces the length of the string step by step until only two digits remain. If the final two digits are the same, we return `True`; otherwise, we return `False`.
# Approach
1. Convert the given string `s` into a new string where each digit is the sum of two adjacent digits modulo 10.
2. Repeat this process until only two digits remain in `s`.
3. Check if the two remaining digits are the same.
4. Return `True` if they are the same, otherwise return `False`.
# Complexity
- Time complexity:
Since we need to traverse entirety of the string and also traverse it each time to reduce its length. Time complexity is $$O(n^2)$$
- Space complexity:
We create a new string in each step, but the total space used is proportional to the input size, so it is $$O(n)$$.
# Code
```python []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
newS = []
for i in range(len(s) - 1):
newS.append(str((int(s[i]) + int(s[i + 1])) % 10))
s = "".join(newS)
return s[0] == s[1]
| 1 | 0 |
['Math', 'String', 'String Matching', 'Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Recursive ✅ - Beats 100% - Python/Java/C++
|
recursive-beats-100-pythonjavac-by-cryan-kvl8
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
cryandrich
|
NORMAL
|
2025-02-23T08:04:04.275920+00:00
|
2025-02-23T08:04:04.275920+00:00
| 9 | 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
```python []
class Solution:
def hasSameDigits(self, s: str) -> bool:
ans = [int(i) for i in s]
while len(ans) > 2:
ans = [(ans[i] + ans[i + 1]) % 10 for i in range(len(ans) - 1)]
return ans[0] == ans[1]
```
```java []
class Solution {
public boolean hasSameDigits(String s) {
int[] ans = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
ans[i] = s.charAt(i) - '0';
}
while (ans.length > 2) {
int[] temp = new int[ans.length - 1];
for (int i = 0; i < ans.length - 1; i++) {
temp[i] = (ans[i] + ans[i + 1]) % 10;
}
ans = temp;
}
return ans[0] == ans[1];
}
}
```
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
vector<int> ans;
for (char c : s) {
ans.push_back(c - '0');
}
while (ans.size() > 2) {
vector<int> temp;
for (size_t i = 0; i < ans.size() - 1; i++) {
temp.push_back((ans[i] + ans[i + 1]) % 10);
}
ans = temp;
}
return ans[0] == ans[1];
}
};
```
| 1 | 0 |
['C++', 'Java', 'Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
easy cpp solution to understand
|
easy-cpp-solution-to-understand-by-prati-00g5
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
pratik5722
|
NORMAL
|
2025-02-23T08:01:25.693849+00:00
|
2025-02-23T08:01:25.693849+00:00
| 9 | 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 []
#pragma GCC optimize("O3", "unroll-loops")
const auto _ = std::cin.tie(nullptr)->sync_with_stdio(false);
#define LC_HACK
#ifdef LC_HACK
const auto __ = []() {
struct ___ { static void _() { std::ofstream("display_runtime.txt") << 0 << '\n'; } };
std::atexit(&___::_);
return 0;
}();
#endif
class Solution {
public:
bool hasSameDigits(string s) {
string ans = "";
while(s.size() > 2){
int n = s.size();
for(int i = 0;i < n-1;i++){
int one = s[i] - '0';
int two = s[i + 1] - '0';
int num = (one + two) % 10;
ans += to_string(num);
}
s = ans;
ans = "";
}
int one = s[0] - '0';
int two = s[1] - '0';
return one == two;
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Repeated Digit Sum Check || String Comparison || Beats 100.00%
|
repeated-digit-sum-check-string-comparis-spcz
|
IntuitionThe problem asks to determine if after repeatedly summing adjacent digits modulo 10, the final two digits are the same. This suggests a simulation appr
|
MLTaza
|
NORMAL
|
2025-02-23T07:05:45.210686+00:00
|
2025-02-23T07:05:45.210686+00:00
| 20 | false |
# Intuition
The problem asks to determine if after repeatedly summing adjacent digits modulo 10, the final two digits are the same. This suggests a simulation approach where we perform the summing operation until we are left with a string of length 2, and then check if the two digits are equal.
# Approach
1. Iterate while the length of the string `s` is greater than 2.
2. In each iteration, create a new string by summing adjacent digits modulo 10.
3. Replace the original string `s` with the new string.
4. After the loop finishes, check if the first and second characters of the remaining string are equal.
5. Return `true` if they are equal, `false` otherwise.
# Complexity
- Time complexity: $$O(n^2)$$
- In the worst case, the loop runs `n-2` times, and each iteration takes `O(n)` time to create the new string.
- Space complexity: $$O(n)$$
- In each iteration, we create a new string of length `n-1`, which takes `O(n)` space.
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
while (s.length() > 2) {
StringBuilder str= new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
int sum = (s.charAt(i) - '0' + s.charAt(i + 1) - '0') % 10;
str.append(sum);
}
s = str.toString();
}
return s.charAt(0) == s.charAt(1);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
"Recursive Digit Reduction to Check for Uniform Digits"
|
recursive-digit-reduction-to-check-for-u-ek1j
|
IntuitionFirst calculating the first operation and then recursively calling the same function with the string we get from the first operation. And recursively c
|
TECH_AJAY
|
NORMAL
|
2025-02-23T07:00:38.698473+00:00
|
2025-02-23T07:00:38.698473+00:00
| 51 | false |
# Intuition
First calculating the first operation and then recursively calling the same function with the string we get from the first operation. And recursively calling the function until we get the two digits.
# Approach
The approach works by reducing the string of digits recursively. For every string:
It iterates over the string and sums adjacent digits.
After summing, it takes the modulo 10 of the result, and the new string is formed by appending these modulo values.
This process continues recursively on the new string sb formed in the current iteration.
Eventually, when the string reduces to a length of 1, the function checks whether all the digits are the same.
# Complexity
# Time complexity:
Processing Each String (Per Recursive Call):
In each recursive call, the string is processed by iterating through it and summing adjacent pairs of digits. The iteration over the string takes O(n) time.
Recursive Depth:
The recursion depth is at most n (since the string length decreases by 1 with each recursive call).
Total Time Complexity:
For each recursive call, we are doing O(n) work, and there are n recursive calls in total. Hence, the overall time complexity is O(n^2).
# Space complexity:
Recursive Call Stack:
The recursion depth is at most the length of the string n. This happens because in each step, we reduce the string by 1.
So, the recursive call stack can go as deep as n.
String Builder (sb):
In each recursive call, a new StringBuilder object is created. This object holds a string of length n-1, n-2, ..., down to 1.
The total space used by the StringBuilder across all recursive calls will sum up to O(n).
# Total Space Complexity:
Recursive call stack space: O(n)
StringBuilder space: O(n) Thus, the total space complexity is O(n).
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
StringBuilder sb = new StringBuilder();
int length = s.length();
if (length == 1) return true;
if(length==2 && s.charAt(0)!=s.charAt(1)) {
return false;
}
for(int i=0;i<length-1;i++){
int sum = 0;
sum+=s.charAt(i)-'0';
sum+=s.charAt(i+1)-'0';
sb.append(sum%10);
}
return hasSameDigits(sb.toString());
}
}
```
| 1 | 0 |
['String', 'Recursion', 'Java']
| 1 |
check-if-digits-are-equal-in-string-after-operations-i
|
<<BEAT 100% SOLUTIONS || BEGINNER FRIENDLY SOLUTIONS>>
|
beat-100-solutions-beginner-friendly-sol-77k3
|
PLEASE UPVOTE MECode
|
Dakshesh_vyas123
|
NORMAL
|
2025-02-23T05:52:57.080970+00:00
|
2025-02-23T05:52:57.080970+00:00
| 33 | false |
# **PLEASE UPVOTE ME**
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.size()>2){
string a;
for(int i=0;i<s.size()-1;i++){
int x=((s[i]-'0')+(s[i+1]-'0'))%10;
a.push_back(x);
}
s=a;
}
if(s[0]==s[1]) return true;
else return false;
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
short and simple
|
short-and-simple-by-tavish_golcha-1cys
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
TAVISH_golcha
|
NORMAL
|
2025-02-23T05:46:21.874586+00:00
|
2025-02-23T05:46:21.874586+00:00
| 8 | 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:
bool hasSameDigits(string s) {
// int digit1,digit2,sumDigit;
while(s.length()>2){
string newString;
// newString.reserve(s.length()-1);
for(int i=0;i<s.length()-1;i++){
int digit1=s[i]-'0';
int digit2=s[i+1]-'0';
int sumDigit=(digit1+digit2)%10;
newString.push_back(sumDigit + '0');
}
s=newString;
}
return s[0]==s[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
3461. Check If Digits Are Equal in String After Operations I - || Easy Python || List || String ||
|
3461-check-if-digits-are-equal-in-string-095d
|
IntuitionThe goal is to iteratively transform the input string by summing adjacent digits and taking the last digit of the sum (modulo 10). This process continu
|
PANDITVIPUL05
|
NORMAL
|
2025-02-23T05:38:44.909398+00:00
|
2025-02-23T05:38:44.909398+00:00
| 54 | false |
# Intuition
The goal is to iteratively transform the input string by summing adjacent digits and taking the last digit of the sum (modulo 10). This process continues until only two digits remain. If the resulting two digits are the same, return True; otherwise, return False.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
1. Initialize a list (res) containing the input string s.
2. Iterate while res[0] has more than two characters:
- Generate a new string where each digit is obtained by summing adjacent digits modulo 10.
- Replace res[0] with this new transformed string.
3. Check the final two-digit result:
- If both digits are the same, return True; otherwise, return False.
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
- Each iteration reduces the length of the string by 1, so it runs approximately O(n) times.
- Within each iteration, constructing the new string takes O(n), leading to an overall complexity of O(n^2 ).
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
- The algorithm maintains a list (res) storing intermediate results, with a maximum size of O(n).
- The space complexity is O(n).
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
res = []
res.append(s)
while len(res[0])!=2:
temp = ''
for i in range(len(res[0])-1):
temp +=str((int(res[0][i])+int(res[0][i+1]))%10)
res.pop()
res.append(temp)
return res[0][0]==res[0][1]
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Python3 || 4 lines, pairwise and map || T/S: 98% / 95%
|
python3-5-lines-pairwise-and-map-ts-x-ms-bglp
|
Here's the plan:
We map the string of digits to a list of single digit integers.
We use pairwise to determine the pair sums, and we use iteration to continue
|
Spaulding_
|
NORMAL
|
2025-02-23T05:16:25.460937+00:00
|
2025-03-17T20:42:44.039971+00:00
| 33 | false |
Here's the plan:
1. We map the string of digits to a list of single digit integers.
2. We use `pairwise` to determine the pair sums, and we use iteration to continue the process until the length of the list is exactly two.
3. We check whether the two list elements are equal.
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
digits = map(int,s) # <-- 1
for _ in range(len(s) - 2): # <-- 2
digits = [(x+y)%10 for x, y in pairwise(digits)]
return digits[0] == digits[1] # <-- 3
```
[https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-i/submissions/1552481786/](https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-i/submissions/1552481786/)
I could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(s)`.
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Most easy approach using char->int approach
|
most-easy-approach-using-char-int-approa-a0jo
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Eclipse27
|
NORMAL
|
2025-02-23T04:39:48.962093+00:00
|
2025-02-23T04:39:48.962093+00:00
| 20 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
while(s.length()>2){
StringBuilder str = new StringBuilder();
for(int i = 0 ; i<s.length()-1 ; i++){
int a = Character.getNumericValue(s.charAt(i));
int b = Character.getNumericValue(s.charAt(i+1));
int c = (a+b)%10;
str.append(c);
}
s = str.toString();
}
if(s.charAt(0) == s.charAt(1)) return true;
return false;
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Easy JAVA Solution || Beats 100%
|
easy-java-solution-beats-100-by-harsh123-c4oc
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Harsh123009
|
NORMAL
|
2025-02-23T04:35:43.656629+00:00
|
2025-02-23T04:35:43.656629+00:00
| 24 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n = s.length();
int[] d = new int[n];
for (int i = 0; i < n; i++) d[i] = s.charAt(i) - '0';
while (n > 2) {
for (int i = 0; i < n - 1; i++) d[i] = (d[i] + d[i + 1]) % 10;
n--;
}
return d[0] == d[1];
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Python solution
|
python-solution-by-kashsuks-ceht
|
Code
|
kashsuks
|
NORMAL
|
2025-02-23T04:23:15.526555+00:00
|
2025-02-23T04:23:15.526555+00:00
| 12 | false |
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
s = ''.join(str((int(s[i]) + int(s[i+1])) % 10) for i in range(len(s) - 1))
return s[0] == s[1]
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple C++ Solution | Weekly Contest 438 | String
|
simple-c-solution-weekly-contest-438-str-fh8v
|
SolutionComplexity
Time complexity:
O(n2)
Space complexity:
O(n)
Code
|
ipriyanshi
|
NORMAL
|
2025-02-23T04:22:57.469778+00:00
|
2025-02-23T04:22:57.469778+00:00
| 30 | false |
# Solution
https://youtu.be/V98ueQ4zVkg
# Complexity
- Time complexity:
$$O(n^2)$$
- Space complexity:
$$O(n)$$
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
string temp = "";
while(s.length() > 2){
for(int i = 0; i < s.length()-1; i++){
temp.push_back((s[i]+s[i+1])%10);
}
s = temp;
temp = "";
}
return s[0] == s[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
[PYTHON] ** 6 Lines of Codes Beats 100% **
|
python-6-lines-of-codes-beats-100-by-ant-l0p9
|
IntuitionAdd the new elements to the end and remove old digits.Complexity
Time complexity:O(n)
Space complexity:O(1)
Code
|
anthony-le-vn
|
NORMAL
|
2025-02-23T04:21:32.978873+00:00
|
2025-02-23T04:21:32.978873+00:00
| 56 | false |
# Intuition
Add the new elements to the end and remove old digits.
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(1)$$
# Code
```python []
class Solution(object):
def hasSameDigits(self, s):
"""
:type s: str
:rtype: bool
"""
while len(s) > 2:
n = len(s)
for i in range(0, n-1):
s += str((int(s[i])+ int(s[i+1]))% 10)
s = s[n:]
return s[0] == s[1]
```
| 1 | 0 |
['Recursion', 'Python']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple C++ Solution | Weekly Contest 438 | String
|
simple-c-solution-weekly-contest-438-str-9253
|
SolutionComplexity
Time complexity:
O(n2)
Space complexity:
O(n)
Code
|
iAmPriyanshi1708
|
NORMAL
|
2025-02-23T04:21:10.686623+00:00
|
2025-02-23T04:21:10.686623+00:00
| 16 | false |
# Solution
# Complexity
- Time complexity:
$$O(n^2)$$
- Space complexity:
$$O(n)$$
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
string temp = "";
while(s.length() > 2){
for(int i = 0; i < s.length()-1; i++){
temp.push_back((s[i]+s[i+1])%10);
}
s = temp;
temp = "";
}
return s[0] == s[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple Python Solution, beat 100% ✅
|
simple-python-solution-beat-100-by-sara5-4jx2
|
Code
|
sara533
|
NORMAL
|
2025-02-23T04:17:04.652225+00:00
|
2025-02-23T04:17:04.652225+00:00
| 40 | false |
# Code
```python3 []
class Solution:
def compute(self, s: str) -> str:
res = ""
for i in range(len(s) - 1):
digit = (int(s[i]) + int(s[i+1])) % 10
res += str(digit)
return res
def hasSameDigits(self, s: str) -> bool:
res = s
while len(res) > 2:
res = self.compute(res)
return res[0] == res[1]
```
| 1 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple Solution
|
simple-solution-by-ankith_kumar-qzpk
|
Complexity
Time complexity: O(N^2)
Space complexity: O(N)
Code
|
Ankith_Kumar
|
NORMAL
|
2025-02-23T04:06:14.902167+00:00
|
2025-02-23T04:06:14.902167+00:00
| 8 | false |
# Complexity
- Time complexity: O(N^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
StringBuilder str = new StringBuilder(s);
while(str.length()>2){
StringBuilder t = new StringBuilder();
for(int i = 0;i<str.length()-1;i++){
int f = str.charAt(i)-'0';
int sec = str.charAt(i+1)-'0';
t.append((char)((f+sec)%10 +'0'));
}
// System.out.println(t.toString());
str = t;
}
return str.charAt(0)==str.charAt(1);
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
✅🔥Easy to Understand | C++ Code
|
easy-to-understand-c-code-by-minavkaria-hmd0
|
ApproachLoop and replace the string till the size of p not becomes 2Code
|
MinavKaria
|
NORMAL
|
2025-02-23T04:02:27.144335+00:00
|
2025-02-23T04:02:27.144335+00:00
| 34 | false |
# Approach
<!-- Describe your approach to solving the problem. -->
Loop and replace the string till the size of p not becomes 2
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
int n = s.size();
int tk = n - 1;
string p = s;
while (p.size() != 2) {
string pp = "";
for (int i = 0; i < p.size() - 1; i++)
{
int a = p[i] - '0';
int b = p[i + 1] - '0';
char t = static_cast<char>(((a + b) % 10+'0'));
pp += t;
}
// cout<<pp<<"\n";
p=pp;
}
return p[0]==p[1];
}
};
```
| 1 | 0 |
['C++']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
java solution
|
java-solution-by-mdshoaib6360-q03z
|
Complexity
Time complexity:0(n)
Space complexity:0(n)
Code
|
mdshoaib6360
|
NORMAL
|
2025-02-23T04:02:12.997851+00:00
|
2025-02-23T04:02:12.997851+00:00
| 24 | false |
# Complexity
- Time complexity:0(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:0(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n=s.length();
if(n==2) return s.charAt(0) ==s.charAt(1);
int[] digits=new int[n];
for(int i=0;i<n;i++){
digits[i]=s.charAt(i)-'0';
}
while(n>2){
for(int i=0;i<n-1;i++){
digits[i]=(digits[i]+digits[i+1])%10;
}
n--;
}
return digits[0]==digits[1];
}
}
```
| 1 | 0 |
['Java']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple Go Solution !!
|
simple-go-solution-by-dipak__patil-73be
|
Code
|
dipak__patil
|
NORMAL
|
2025-02-23T04:01:37.176798+00:00
|
2025-02-23T04:01:37.176798+00:00
| 33 | false |
# Code
```golang []
func hasSameDigits(s string) bool {
currList := []byte(s)
insertPos := 0
for len(currList) > 2 {
insertPos = 0
for i := 1; i < len(currList); i++ {
currList[insertPos] = (byte(int(currList[i-1]-'0')+int(currList[i]-'0')) % 10) + '0'
insertPos++
}
currList = currList[:len(currList)-1]
}
return currList[0] == currList[1]
}
```
| 1 | 0 |
['Go']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple and clean approach
|
simple-and-clean-approach-by-manedeepu73-9gxm
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
manedeepu73
|
NORMAL
|
2025-04-12T08:37:57.611896+00:00
|
2025-04-12T08:37:57.611896+00:00
| 1 | 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} s
* @return {boolean}
*/
var hasSameDigits = function(s) {
let i =0
let currentS = ''
while(s.length > 2){
let sum = (Number(s[i]) + (Number(s[i+1]) || 0)) % 10
currentS += sum
if( i === s.length - 2){
i = 0
s = currentS
currentS = ''
} else {
i += 1
}
}
return s[0] === s[1]
};
```
| 0 | 0 |
['JavaScript']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
My 88th Problem
|
my-88th-problem-by-chefcurry4-22sy
|
ApproachWe iteratively reduce the input string s by replacing it with a new string where each character is the sum modulo 10 of every pair of consecutive digits
|
Chefcurry4
|
NORMAL
|
2025-04-12T06:48:51.889314+00:00
|
2025-04-12T06:48:51.889314+00:00
| 1 | false |
# Approach
We iteratively reduce the input string `s` by replacing it with a new string where each character is the sum modulo 10 of every pair of consecutive digits in `s`.
This is repeated until only two digits remain.
We then return True if the final two digits are the same, otherwise False.
# Complexity
- Time complexity:
$$O(n^2)$$
At each step, the string size decreases by 1 (from n to n-1 to n-2...), so the total number of operations is:
$$(n-1) + (n-2) + \dots + 1 = O(n^2)$$
- Space complexity:
$$O(n)$$
We create a new string in each iteration of length (len(s) - 1), which in total is bounded by O(n) space.
# Code
```python []
class Solution(object):
def hasSameDigits(self, s):
while len(s) > 2:
new_s = ""
for i in range(len(s) - 1):
summed = (int(s[i]) + int(s[i + 1])) % 10
new_s += str(summed)
s = new_s
return s[0] == s[1]
"""
:type s: str
:rtype: bool
"""
```
| 0 | 0 |
['Math', 'String', 'Simulation', 'Combinatorics', 'Number Theory', 'Python']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
Simple and Easy User Friendly Code
|
simple-and-easy-user-friendly-code-by-ba-flrr
|
IntuitionThe problem asks to repeatedly sum adjacent digits modulo 10 until a two-digit number is obtained. Then, check if both digits are the same. A straightf
|
Balarakesh
|
NORMAL
|
2025-04-11T16:21:33.986540+00:00
|
2025-04-11T16:21:33.986540+00:00
| 1 | false |
# Intuition
The problem asks to repeatedly sum adjacent digits modulo 10 until a two-digit number is obtained. Then, check if both digits are the same. A straightforward iterative approach seems suitable.
# Approach
1. Iterate while the length of the input string `s` (or `num` in the code) is not 2.
2. In each iteration, create a new string `num_str` by summing adjacent digits of the current string `num`, taking the result modulo 10, and appending it to `num_str`.
3. Update `num` with `num_str`.
4. After the loop terminates (when `num` has length 2), check if the first and second digits of `num` are equal.
5. Return `True` if they are equal, `False` otherwise.
# Complexity
- Time complexity:
$$O(n^2)$$ where n is the length of the input string. In the worst case, each iteration reduces the length of the string by 1, and each iteration performs a linear scan of the string.
- Space complexity:
$$O(n)$$ where n is the length of the input string, due to the creation of the `num_str` in each iteration.
# Code
```python3
class Solution:
def hasSameDigits(self, s: str) -> bool:
num = s
while len(num) != 2:
num_str = ""
for i in range(len(num) - 1):
digit_sum = int(num[i]) + int(num[i+1])
num_str += str(digit_sum % 10)
num = num_str
return num[0] == num[1]
| 0 | 0 |
['Python3']
| 0 |
check-if-digits-are-equal-in-string-after-operations-i
|
submission beat 91% of other submissions' runtime|| tc->o(n) || sc->o(1)||
|
submission-beat-91-of-other-submissions-6wmpc
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Rohan07_6473
|
NORMAL
|
2025-04-11T09:02:12.384893+00:00
|
2025-04-11T09:02:12.384893+00:00
| 0 | 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:
bool hasSameDigits(string s) {
while(s.size()>2){
string c = "";
for(int i =0 ;i<s.size()-1 ; i++){
int a = s[i]-'0'; //convert to the integer
int b = s[i+1]-'0';//convert to the integer
int sum = (a+b)%10;
c.push_back(sum + '0'); //convert to string
}
s = c;
}
return s[0] == s[1];
}
};
```
| 0 | 0 |
['C++']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.