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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
finding-mk-average | Use 3 TreeMap + Queue | use-3-treemap-queue-by-ruinan-dyz5 | Intuition\n1. Tried 3 PQ and each time when calculateMKAverage, traverse small and large PQ to calculate the sum for them == LTE\n2. Tried 3 TreeMap, but did no | ruinan | NORMAL | 2024-09-29T23:30:49.442548+00:00 | 2024-09-29T23:30:49.442584+00:00 | 12 | false | # Intuition\n1. Tried 3 PQ and each time when calculateMKAverage, traverse small and large PQ to calculate the sum for them == LTE\n2. Tried 3 TreeMap, but did not use the balance method, rather than, apply moveToSmall, moveToLarge to recursively balance the Map == Stack Overflow\n\n# Approach\nMaintain 3 TreeMap, first one to store the smallest k elements, and the last one to store the largest k elements, the rest are staying in the midBucket. \n\nWhen we need to add a new element, check the window if its size is smaller than m, if it is, directly add it to the potential bucket. If not, remove the earliest element, fetch from queue head, then add it to the potential bucket. \n\nBalance the buckets.\n\n# Complexity\n- Time complexity:\n`O(klogk + mlogm)`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m)\n\n# Code\n```java []\n\n\nclass MKAverage {\n int m;\n int k;\n TreeMap<Integer, Integer> lowBucket;\n TreeMap<Integer, Integer> midBucket;\n TreeMap<Integer, Integer> highBucket;\n long midBucketSum; // prevent overflow\n long smallSum;\n long largeSum;\n int lowBucketSize;\n int highBucketSize;\n Deque<Integer> stream;\n\n public MKAverage(int m, int k) {\n this.m = m;\n this.k = k;\n this.lowBucket = new TreeMap<>();\n this.midBucket = new TreeMap<>();\n this.highBucket = new TreeMap<>();\n this.midBucketSum = 0;\n this.smallSum = 0;\n this.largeSum = 0;\n this.lowBucketSize = 0;\n this.highBucketSize = 0;\n this.stream = new ArrayDeque<>(); // Can use linkedlist here\n }\n\n public void addElement(int num) {\n // directly add the element\n if (lowBucket.isEmpty() || num <= lowBucket.lastKey()) {\n lowBucket.merge(num, 1, Integer::sum);\n smallSum += num;\n lowBucketSize++;\n } else if (highBucket.isEmpty() || num >= highBucket.firstKey()) {\n highBucket.merge(num, 1, Integer::sum);\n largeSum += num;\n highBucketSize++;\n } else {\n midBucket.merge(num, 1, Integer::sum);\n midBucketSum += num;\n }\n\n stream.offer(num);\n // remove the earliest element added\n if (stream.size() > m) {\n int oldestNum = stream.poll();\n if (lowBucket.containsKey(oldestNum)) {\n removeElementFromBucket(lowBucket, oldestNum);\n smallSum -= oldestNum;\n lowBucketSize--;\n } else if (highBucket.containsKey(oldestNum)) {\n removeElementFromBucket(highBucket, oldestNum);\n largeSum -= oldestNum;\n highBucketSize--;\n } else {\n removeElementFromBucket(midBucket, oldestNum);\n midBucketSum -= oldestNum;\n }\n }\n // most important step, balance the tree.\n balanceBuckets();\n }\n\n public int calculateMKAverage() {\n if (stream.size() < m) {\n return -1;\n }\n return (int) (midBucketSum / (m - 2 * k));\n }\n\n private void balanceBuckets() {\n // Prevent to recursively move the elements, it will cause Stack Overflow.\n while (lowBucketSize > k) {\n int largestInLow = lowBucket.lastKey();\n removeElementFromBucket(lowBucket, largestInLow);\n smallSum -= largestInLow;\n lowBucketSize--;\n\n midBucket.merge(largestInLow, 1, Integer::sum);\n midBucketSum += largestInLow;\n }\n\n while (highBucketSize > k) {\n int smallestInHigh = highBucket.firstKey();\n removeElementFromBucket(highBucket, smallestInHigh);\n largeSum -= smallestInHigh;\n highBucketSize--;\n\n midBucket.merge(smallestInHigh, 1, Integer::sum);\n midBucketSum += smallestInHigh;\n }\n\n while (lowBucketSize < k && !midBucket.isEmpty()) {\n int smallestInMid = midBucket.firstKey();\n removeElementFromBucket(midBucket, smallestInMid);\n midBucketSum -= smallestInMid;\n\n lowBucket.merge(smallestInMid, 1, Integer::sum);\n smallSum += smallestInMid;\n lowBucketSize++;\n }\n\n while (highBucketSize < k && !midBucket.isEmpty()) {\n int largestInMid = midBucket.lastKey();\n removeElementFromBucket(midBucket, largestInMid);\n midBucketSum -= largestInMid;\n\n highBucket.merge(largestInMid, 1, Integer::sum);\n largeSum += largestInMid;\n highBucketSize++;\n }\n }\n\n private void removeElementFromBucket(TreeMap<Integer, Integer> bucket, int num) {\n bucket.put(num, bucket.get(num) - 1);\n if (bucket.get(num) == 0) {\n bucket.remove(num);\n }\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
finding-mk-average | ✅ Production ready c++ code | production-ready-c-code-by-rohanprakash-xlpj | Intuition\nThe problem is to compute the moving average of a data stream while excluding the smallest and largest elements to prevent extreme values from skewin | RohanPrakash | NORMAL | 2024-09-28T05:22:13.426310+00:00 | 2024-09-28T05:22:13.426333+00:00 | 34 | false | # Intuition\nThe problem is to compute the moving average of a data stream while excluding the smallest and largest elements to prevent extreme values from skewing the results. This requires maintaining a dynamic set of the most recent data points such that we can efficiently calculate the average of the middle values at any point in time.\n\n# Approach\nThe class utilizes three multisets to store different parts of the data:\n\n1. smallestElements: Stores the smallest values.\n2. middleElements: Stores the middle values whose average is calculated\n3. largestElements: Contains the largest values.\n\n# Key Operations\n1. **Inserting Data:** As new data arrives, it is first placed into smallestElements. If this set exceeds its size limit, the largest element in smallestElements is moved to middleElements, and similarly from middleElements to largestElements if needed.\n2. **Removing Data:** When data needs to be removed (as the window moves), it is taken out from the appropriate set and the sets are rebalanced just like during insertion.\n3. **Calculating Average:** The average is calculated using the sum of middleElements, divided by its size.\n\n# Complexity\n#### Time complexity:\n1. Insertion and Removal: O(log k) for each operation, where k is the number of elements within the window. This is due to the log-time complexity for insertion and deletion operations in a multiset.\n2. Rebalancing: Each rebalancing operation, moving an element between sets, also takes O(log k).\n\n#### Space complexity:\nO(m), where m is the size of the moving window. This space is used to store elements in three multisets and an array that keeps the recent elements of the stream.\n\n# Code\n```cpp []\nclass MKAverage {\n int windowSize; // Total number of elements in the moving window\n int exclusionCount; // Number of elements to exclude from both ends\n int middleSectionSize; // Size of the middle section containing valid elements\n int currentPosition; // Current insertion position in the cyclic buffer\n long middleSectionSum; // Sum of elements in the middle section\n vector<int> recentElements; // Cyclic buffer to store recent elements up to windowSize\n multiset<int> smallestElements, middleElements, largestElements; // Multisets to manage window partitions\n \n public:\n MKAverage(int m, int k): windowSize(m), exclusionCount(k),\n middleSectionSize(m - 2 * k), currentPosition(0), middleSectionSum(0) {\n recentElements.resize(m);\n }\n \n void addElement(int num) {\n // Remove the element that is sliding out of the window if the window is full\n if (currentPosition >= windowSize)\n removeElement(recentElements[currentPosition % windowSize]);\n \n // Add the new element into the data structure\n insertElement(num);\n // Store the new element in the cyclic buffer\n recentElements[currentPosition % windowSize] = num;\n currentPosition++;\n }\n\n void removeElement(int number) {\n // Remove the number from the appropriate set\n if (number <= *rbegin(smallestElements))\n smallestElements.erase(smallestElements.find(number));\n else if (number <= *rbegin(middleElements)) {\n auto it = middleElements.find(number);\n middleSectionSum -= *it;\n middleElements.erase(it);\n } else\n largestElements.erase(largestElements.find(number));\n\n // Rebalance the sets if necessary\n if (smallestElements.size() < exclusionCount) {\n smallestElements.insert(*begin(middleElements));\n middleSectionSum -= *begin(middleElements);\n middleElements.erase(begin(middleElements));\n }\n if (middleElements.size() < middleSectionSize) {\n middleElements.insert(*begin(largestElements));\n middleSectionSum += *begin(largestElements);\n largestElements.erase(begin(largestElements));\n }\n }\n\n void insertElement(int number) {\n smallestElements.insert(number);\n if (smallestElements.size() > exclusionCount) {\n auto it = prev(end(smallestElements));\n middleElements.insert(*it);\n middleSectionSum += *it;\n smallestElements.erase(it);\n }\n if (middleElements.size() > middleSectionSize) {\n auto it = prev(end(middleElements));\n middleSectionSum -= *it;\n largestElements.insert(*it);\n middleElements.erase(it);\n }\n }\n \n int calculateMKAverage() {\n if (currentPosition < windowSize) return -1; // Not enough elements to calculate the average\n return middleSectionSum / middleSectionSize; // Return the average of the middle section\n }\n};\n\n/**\n * Your MKAverage object will be instantiated and called as such:\n * MKAverage* obj = new MKAverage(m, k);\n * obj->addElement(num);\n * int param_2 = obj->calculateMKAverage();\n */\n``` | 0 | 0 | ['C++'] | 0 |
add-to-array-form-of-integer | 🔥🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3 || Java | simplest-solutionfull-explanationc-pytho-4pno | Consider\uD83D\uDC4D\n\n Please Upvote If You Find It Helpful\n\n# Intuition\nWe are taking k as carry.\nWe start from the last or lowest dig | naman_ag | NORMAL | 2023-02-15T01:49:33.396974+00:00 | 2023-02-15T02:27:32.758241+00:00 | 26,764 | false | # Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nWe are taking `k` as carry.\nWe start from the last or lowest digit in array `num` add `k`.\nThen **update** `k` and move untill the highest digit.\nAfter traversing array if carry is **>** `0` then we add it to begining of `num`.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Example: `num` = [2,1,5], `k` = 806\n At index 2 num = [2, 1, 811] \n So, `k` = 81 and `num` = [2, 1, 1]\n\n At index 1 num = [2, 82, 1]\n So, `k` = 8 and `num` = [2, 2, 1]\n\n At index 0 num = [10, 2, 1]\n So, `k` = 1 and `num` = [0, 2, 1]\n\n Now `k` > 0\n So, we add at the beginning of num\n `num` = [1, 0, 2, 1]\n\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```C++ []\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n for(int i=num.size()-1;i>=0;i--){\n num[i] += k;\n k = num[i]/10;\n num[i] %= 10;\n }\n while(k > 0){\n num.insert(num.begin(), k%10);\n k /= 10;\n }\n return num;\n }\n};\n```\n```python []\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n for i in range(len(num) - 1, -1, -1):\n k, num[i] = divmod(num[i] + k, 10)\n while k:\n k, a = divmod(k, 10)\n num = [a] + num\n return num\n```\n```Java []\npublic List<Integer> addToArrayForm(int[] num, int K) {\n List<Integer> res = new LinkedList<>();\n for (int i = num.length - 1; i >= 0; --i) {\n res.add(0, (num[i] + K) % 10);\n K = (num[i] + K) / 10;\n }\n while (K > 0) {\n res.add(0, K % 10);\n K /= 10;\n }\n return res;\n}\n```\n\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/) | 357 | 1 | ['Array', 'Python', 'C++', 'Java', 'Python3'] | 21 |
add-to-array-form-of-integer | [Java/C++/Python] Take K itself as a Carry | javacpython-take-k-itself-as-a-carry-by-g9mh0 | Explanation\nTake K as a carry.\nAdd it to the lowest digit,\nUpdate carry K,\nand keep going to higher digit.\n\n\n## Complexity\nInsert will take O(1) time or | lee215 | NORMAL | 2019-02-10T04:04:03.694782+00:00 | 2020-08-18T03:39:15.820573+00:00 | 32,009 | false | ## **Explanation**\nTake `K` as a carry.\nAdd it to the lowest digit,\nUpdate carry `K`,\nand keep going to higher digit.\n<br>\n\n## **Complexity**\nInsert will take `O(1)` time or `O(N)` time on shifting, depending on the data stucture.\nBut in this problem `K` is at most 5 digit so this is restricted.\nSo this part doesn\'t matter.\n\nThe overall time complexity is `O(N)`.\nFor space I\'ll say `O(1)`\n<br>\n\n**Java**\n```java\n public List<Integer> addToArrayForm(int[] A, int K) {\n List<Integer> res = new LinkedList<>();\n for (int i = A.length - 1; i >= 0; --i) {\n res.add(0, (A[i] + K) % 10);\n K = (A[i] + K) / 10;\n }\n while (K > 0) {\n res.add(0, K % 10);\n K /= 10;\n }\n return res;\n }\n```\n**Java**\nWith one loop.\n```java\n public List<Integer> addToArrayForm(int[] A, int K) {\n List res = new LinkedList<>();\n for (int i = A.length - 1; i >= 0 || K > 0; --i) {\n res.add(0, (i >= 0 ? A[i] + K : K) % 10);\n K = (i >= 0 ? A[i] + K : K) / 10;\n }\n return res;\n }\n```\n\n**C++:**\n```cpp\n vector<int> addToArrayForm(vector<int> A, int K) {\n for (int i = A.size() - 1; i >= 0 && K > 0; --i) {\n A[i] += K;\n K = A[i] / 10;\n A[i] %= 10;\n }\n while (K > 0) {\n A.insert(A.begin(), K % 10);\n K /= 10;\n }\n return A;\n }\n```\n\n**Python:**\n```py\n def addToArrayForm(self, A, K):\n for i in range(len(A) - 1, -1, -1):\n K, A[i] = divmod(A[i] + K, 10)\n return [int(i) for i in str(K)] + A if K else A\n```\n | 337 | 6 | [] | 49 |
add-to-array-form-of-integer | ✅ [JAVA] : Simple | O(max(n, logk)) | No Reverse | Efficient | Explained | java-simple-omaxn-logk-no-reverse-effici-cnt3 | Please UPVOTE if you find this post useful :)\n\nRefer to the following github repsitory for more leetcode solutions\nhttps://github.com/Akshaya-Amar/LeetCodeSo | akshayaamar05 | NORMAL | 2021-06-21T11:03:43.650557+00:00 | 2022-02-04T11:24:43.798414+00:00 | 7,987 | false | # **Please UPVOTE if you find this post useful :)**\n\n<u><strong>Refer to the following github repsitory for more leetcode solutions<strong></u>\nhttps://github.com/Akshaya-Amar/LeetCodeSolutions\n\n* <u>**COMPLEXITY**</u>\n\t* **Time: O(max(n, log<sub>10</sub>(k)))**, where **n** is the **length of the array** and **log<sub>10</sub>(k)** is the **number of digits** present in variable `k`.\n\t* **Space: O(max(n, log<sub>10</sub>(k)))**, not an in-place as we need space equal to the given k or length of array, whichever is maximum between the two, to store the elements.\n\n* <u>**BASIC IDEA**</u>\nBasic Idea behind this implementation is to add the num array element one by one with the k\neg:\n`num[] = {1, 2, 3}` and `k = 45;`\n\n\t* **1<sup>st</sup> Iteration:**\n`k += num[len--]` --> k = k + num[2] --> k = 45 + 3 --> k = 48\n`list.addFirst(k % 10)` --> list.addFirst(48 % 10) --> list.addFirst(8) --> [8] \n`k /= 10` --> k = k / 10 --> 48 / 10 --> k = 4\n\n\t* **2<sup>nd</sup> Iteration:**\n`k += num[len--]` --> k = k + num[1] --> k = 4 + 2 --> k = 6\n`list.addFirst(k % 10)` --> list.addFirst(6 % 10) --> list.addFirst(6) --> [6, 8]\n`k /= 10` --> k = k / 10 --> 6 / 10 --> k = 0\n\n\t* **3<sup>rd</sup> Iteration:**\n`k += num[len--]` --> k = k + num[0] --> k = 0 + 1 --> k = 1\n`list.addFirst(k % 10)` --> list.addFirst(1 % 10) --> list.addFirst(1) --> [1, 6, 8] **<--- Desired Output**\n`k /= 10` --> k = k / 10 --> 1 / 10 --> k = 0\n\n\t**Here, the loop will be executed 3 times as (length of num) > (number of digits in k) i.e. O(max(n, log<sub>10</sub>(k))), where n is the length of the array and log<sub>10</sub>(k) is the number of digits**\n\n<iframe src="https://leetcode.com/playground/UiX43koL/shared" frameBorder="0" width="100%" height="400"></iframe>\n\n<u><strong>Refer to the following github repsitory for more leetcode solutions<strong></u>\nhttps://github.com/Akshaya-Amar/LeetCodeSolutions\n\n# **Please UPVOTE if you find this post useful :)** | 111 | 2 | ['Java'] | 9 |
add-to-array-form-of-integer | ✅ Java | Easy | Two Approaches | Math | 100% faster | java-easy-two-approaches-math-100-faster-o6z3 | Approach 1\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n LinkedList<Integer> res=new LinkedList<>();\n int ca | kalinga | NORMAL | 2023-02-15T04:21:22.751854+00:00 | 2023-02-15T04:21:22.751889+00:00 | 9,300 | false | **Approach 1**\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n LinkedList<Integer> res=new LinkedList<>();\n int carry=0;\n int i=0;\n\t\t/*We always start computing from array\'s last element and k\'s last digit and will \n\t\tcompute sum and carry. We will iterate it till k and index of array both have existance. \n\t\tIf one of them gets exhausted the for loop below will not work.*/\n for(i=num.length-1;i>=0 && k>0;i--){\n int temp=num[i];\n res.addFirst((temp+carry+(k%10))%10);\n carry=(temp+carry+(k%10))/10;\n k/=10;\n }\n\t\t/*If for an instance your k is greater than the number that is present in the form of \n\t\tarray then the below while loop will work.*/\n while(k!=0){\n int compute=(k%10)+carry;\n res.addFirst(compute%10);\n carry=compute/10;\n k/=10;\n }\n\t\t/*If for an instance the number that is present in the form of array is greater than k \n\t\tthen the below for loop will work.*/\n for(int r=i;r>=0;r--){\n int temp=num[r];\n res.addFirst((temp+carry)%10);\n carry=(temp+carry)/10;\n }\n\t\t/*If there is some carry still remaining at last then add it to beginning of the \n\t\tarraylist or linkedlist.*/\n if(carry!=0)\n res.addFirst(carry);\n return res;\n }\n}\n```\n\n**Approach 2 (incase someone doesn\'t want to use LinkedList that is used in Approach 1 and want to use ArrayList only)**\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> res=new ArrayList<>();\n int carry=0;\n int i=0;\n for(i=num.length-1;i>=0 && k>0;i--){\n int temp=num[i];\n res.add(0,(temp+carry+(k%10))%10);\n carry=(temp+carry+(k%10))/10;\n k/=10;\n }\n while(k!=0){\n int compute=(k%10)+carry;\n res.add(0,compute%10);\n carry=compute/10;\n k/=10;\n }\n for(int r=i;r>=0;r--){\n int temp=num[r];\n res.add(0,(temp+carry)%10);\n carry=(temp+carry)/10;\n }\n if(carry!=0)\n res.add(0,carry);\n return res;\n }\n}\n```\n\n**Approach 3**\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n LinkedList<Integer> res=new LinkedList<>();\n int len=num.length-1;\n while(len>=0 || k>0){\n if(len>=0){\n k+=num[len--];\n }\n res.addFirst(k%10);\n k/=10;\n }\n return res;\n }\n}\n```\n\n\n | 90 | 0 | ['Array', 'Linked List', 'Math', 'Java'] | 5 |
add-to-array-form-of-integer | C++| FAST AND EFFICIENT | with explanation | c-fast-and-efficient-with-explanation-by-h94b | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome\n\nContinuin | aarindey | NORMAL | 2021-06-14T20:13:20.320348+00:00 | 2023-02-16T07:49:14.725472+00:00 | 6,691 | false | **Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome**\n\nContinuing the example of 123 + 912, we start with [1, 2, 3+912]. Then we perform the addition 3+912, leaving 915. The 5 stays as the digit, while we \'carry\' 910 into the next column which becomes 91.\n\nWe repeat this process with [1, 2+91, 5]. We have 93, where 3 stays and 90 is carried over as 9. Again, we have [1+9, 3, 5] which transforms into [1, 0, 3, 5].\n```\nclass Solution {\npublic:\nvector<int> addToArrayForm(vector<int> A, int K) {\n for(int i=A.size()-1;i>=0&&K>0;i--)\n {\n A[i]+=K;\n K=A[i]/10;\n A[i]%=10;\n }\n while(K>0)\n {\n A.insert(A.begin(),K%10);\n K/=10;\n } \n return A;\n }\n}; | 78 | 1 | ['C'] | 6 |
add-to-array-form-of-integer | C++✅✅ | Faster🧭 than 95%🔥 | NO SHORTCUT MEHTHOD❗❗❗ | Self Explanatory Code | | c-faster-than-95-no-shortcut-mehthod-sel-7s00 | Code\n\n# Please Do Upvote!!!!\n##### Connect with me on Linkedin -> https://www.linkedin.com/in/md-kamran-55b98521a/\n\n\n\nclass Solution {\npublic:\n\n ve | mr_kamran | NORMAL | 2023-02-15T02:27:30.550184+00:00 | 2023-02-15T02:48:22.590804+00:00 | 13,068 | false | # Code\n\n# Please Do Upvote!!!!\n##### Connect with me on Linkedin -> https://www.linkedin.com/in/md-kamran-55b98521a/\n\n```\n\nclass Solution {\npublic:\n\n vector<int> addToArrayForm(vector<int>& num, int k) {\n \n int carry = 0;\n int j = num.size() - 1;\n\n while(j >= 0)\n {\n\n int sum = num[j] + (k % 10) + carry;\n k /= 10;\n\n num[j--] = sum % 10;\n carry = sum/10;\n\n }\n\n while(k > 0)\n {\n\n int sum = (k % 10) + carry;\n k /= 10;\n \n num.insert(num.begin(), sum%10);\n carry = sum/10;\n \n }\n\n if(carry > 0) num.insert(num.begin(), carry);\n \n return num;\n }\n};\n\n```\n | 69 | 1 | ['C++'] | 8 |
add-to-array-form-of-integer | Day 46 || C++ || Easiest Beginner Friendly Sol || O(max(N, log K)) time and O(max(N, log K)) space | day-46-c-easiest-beginner-friendly-sol-o-sfm1 | Intuition of this Problem:\n Describe your first thoughts on how to solve this problem. \nNOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITE | singhabhinash | NORMAL | 2023-02-15T01:02:04.571471+00:00 | 2023-02-15T01:02:04.571511+00:00 | 6,624 | false | # Intuition of this Problem:\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Initialize an empty vector "ans" to store the final result\n2. Initialize "carry" to 0 and "i" to the index of the last digit of "num"\n3. Loop while there is a digit left in k, or there are digits left in num, or there is a carry value.\n4. Compute the sum by adding the carry, the last digit of k (if k has digits left) and the i-th digit of num (if num has digits left).\n5. Compute the carry by taking the sum divided by 10.\n6. Add the digit to the front of the "ans" vector by taking the sum modulo 10.\n7. Decrement i and divide k by 10 (if applicable).\n8. Reverse the "ans" vector and return it.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int> ans;\n int n = num.size();\n int carry = 0, i = n-1;\n while (k > 0 || i >= 0 || carry > 0) {\n int sum = carry;\n if (k > 0) {\n int remainder = k % 10;\n sum += remainder;\n k = k / 10;\n }\n if (i >= 0) {\n sum += num[i];\n i--;\n }\n carry = sum / 10;\n ans.push_back(sum % 10);\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> ans = new ArrayList<>();\n int n = num.length;\n int carry = 0, i = n-1;\n while (k > 0 || i >= 0 || carry > 0) {\n int sum = carry;\n if (k > 0) {\n int remainder = k % 10;\n sum += remainder;\n k = k / 10;\n }\n if (i >= 0) {\n sum += num[i];\n i--;\n }\n carry = sum / 10;\n ans.add(0, sum % 10);\n }\n return ans;\n }\n}\n\n```\n```Python []\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n ans = []\n n = len(num)\n carry = 0\n i = n - 1\n while k > 0 or i >= 0 or carry > 0:\n sum = carry\n if k > 0:\n remainder = k % 10\n sum += remainder\n k //= 10\n if i >= 0:\n sum += num[i]\n i -= 1\n carry = sum // 10\n ans.insert(0, sum % 10)\n return ans\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(max(N, log K))**, where N is the number of digits in "num" and K is the value of "k". We have to iterate over all digits in both "num" and "k" to compute the sum.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(max(N, log K))**, since the size of the output vector can be at most max(N, log K) + 1.\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 35 | 1 | ['Array', 'Math', 'C++', 'Java', 'Python3'] | 4 |
add-to-array-form-of-integer | C++ Well Commented Solution [With Explanation] [100%] | c-well-commented-solution-with-explanati-t6kh | \n/* An important observation ---\n1) num%10 gives us the last digit of a number\n2) num = num/10 cuts off the last digit of the number \n3) numVector.back() gi | just__a__visitor | NORMAL | 2019-02-10T04:36:32.493440+00:00 | 2019-02-10T04:36:32.493485+00:00 | 3,722 | false | ```\n/* An important observation ---\n1) num%10 gives us the last digit of a number\n2) num = num/10 cuts off the last digit of the number \n3) numVector.back() gives us the last digit of the number in vector form\n4) numVector.pop_back() cuts off the last digit of the number in vector form\n5) The extra space required can be reduced by overwriting the first vector. \n*/\n\n\nclass Solution\n{\npublic:\n vector<int> addToArrayForm(vector<int>& a, int k);\n};\n\n/* Returns the sum of 2 numbers in vector form */\nvector<int> Solution :: addToArrayForm(vector<int>& a, int k)\n{\n // Get the length of the first number\n int n = a.size();\n \n // Vector to store the answer\n vector<int> answer;\n \n /* Start adding both the numbers from the end */\n \n int carry = 0;\n // As long as one of the number exists, keep adding them\n while(!a.empty() || k!=0)\n {\n // Get the last digits of both the numbers. If a vector has finished off, the last digit is zero\n int lastDigit_1 = a.empty() ? 0 : a.back();\n int lastDigit_2 = k%10;\n \n // Sum up the digits and add the carry\n int sum = lastDigit_1 + lastDigit_2 + carry;\n answer.push_back(sum%10);\n carry = sum/10;\n \n // Remove the last digits of both the numbers\n if(!a.empty()) a.pop_back();\n k = k/10;\n }\n \n // If the carry is remaining, add it\n if(carry!=0) answer.push_back(carry);\n \n // Reverse the answer, since we were summing up from the end\n reverse(answer.begin(), answer.end());\n \n // Return the answer in vector format\n return answer;\n}\n``` | 35 | 5 | [] | 6 |
add-to-array-form-of-integer | [Java/Python 3] 6 liner w/ comment and analysis | javapython-3-6-liner-w-comment-and-analy-1jev | Note:\n\nI read several other java solutions, and found ArrayList.add(0, K % 10) was used, and it is not O(1) but O(n) instead. \n\nLinkedList.add(0, i) or offe | rock | NORMAL | 2019-02-10T04:59:06.218448+00:00 | 2020-07-15T15:29:07.434140+00:00 | 5,039 | false | # **Note:**\n\nI read several other java solutions, and found `ArrayList.add(0, K % 10)` was used, and it is not `O(1)` but `O(n)` instead. \n\n`LinkedList.add(0, i)` or `offerFirst(i)` is `O(1)`.\n\nCorrect me if I am wrong.\n\n```java\n public List<Integer> addToArrayForm(int[] A, int K) {\n LinkedList<Integer> ans = new LinkedList<>();\n for (int i = A.length - 1; K > 0 || i >= 0; --i, K /= 10) { // loop through A and K, from right to left.\n K += i >= 0 ? A[i] : 0; // Use K as carry over, and add A[i].\n ans.offerFirst(K % 10); // add the least significant digit of K.\n }\n return ans;\n }\n```\t\n```python\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n ans, i = [], len(A) - 1\n while K > 0 or i >= 0:\n K, rmd = divmod(K + (A[i] if i >= 0 else 0), 10)\n ans.append(rmd)\n i -= 1\n return reversed(ans)\n```\n**Analysis:**\n\n**Time & space: O(n + logK)**, where n = A.length. | 28 | 4 | [] | 10 |
add-to-array-form-of-integer | Java Solution (optimal and simple) | java-solution-optimal-and-simple-by-simr-l29w | \'\'\'\nclass Solution {\n public List addToArrayForm(int[] num, int k) {\n \n final LinkedList result = new LinkedList<>();\n int len = | simrananand | NORMAL | 2022-02-17T00:36:50.338685+00:00 | 2022-02-17T00:36:50.338717+00:00 | 2,740 | false | \'\'\'\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n \n final LinkedList<Integer> result = new LinkedList<>();\n int len = num.length - 1;\n \n while(len >= 0 || k != 0){\n \n if(len >= 0){\n k += num[len];\n\t\t\t\tlen--;\n }\n \n result.addFirst(k % 10);\n k /= 10;\n }\n \n return result;\n \n }\n}\n\'\'\' | 25 | 1 | ['Linked List', 'Java'] | 2 |
add-to-array-form-of-integer | (C++) [Very Easy To Understand] | c-very-easy-to-understand-by-not_a_cp_co-z6sw | \nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& A, int K) {\n vector<int> ans;\n int carry = 0, i = A.size()-1;\n | not_a_cp_coder | NORMAL | 2020-07-19T10:54:59.285121+00:00 | 2020-07-19T10:54:59.285170+00:00 | 3,536 | false | ```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& A, int K) {\n vector<int> ans;\n int carry = 0, i = A.size()-1;\n while(i>=0 || carry > 0 || K!=0){\n if(K!=0){\n carry += K%10;\n K = K/10;\n }\n if(i>=0){\n carry += A[i];\n i--; \n }\n ans.push_back(carry%10);\n carry = carry/10;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n```\nFeel free to ask any doubts in the **comment** section and I will respond **ASAP**.\nIf you like this solution, do **UPVOTE**.\nHappy Coding :) | 23 | 1 | ['Math', 'C', 'C++'] | 3 |
add-to-array-form-of-integer | JavaScript Solution with Full Explanation | javascript-solution-with-full-explanatio-vf7o | Please upvote if you find the solution helpful.\n\n\nvar addToArrayForm = function(num, k) {\n\n let i = num.length - 1;\n let res = [];\n while(i >= 0 | SOURADIP22 | NORMAL | 2021-09-05T13:51:17.939588+00:00 | 2021-09-05T13:51:17.939627+00:00 | 1,853 | false | *Please upvote if you find the solution helpful.*\n\n```\nvar addToArrayForm = function(num, k) {\n\n let i = num.length - 1;\n let res = [];\n while(i >= 0 || k >0 ){\n\t\t//this is the general check : taking the last elemnt and adding it with the k value then take the carry(if any to the next iteration) \n if(i >= 0){\n res.push((num[i] + k) % 10);\n k = Math.trunc((num[i] + k) / 10);\n\t\t\ti--;\t\n } \n\t\t//this else block will handle the edge case when we need to increase the array length based on k value\n\t\telse {\n res.push( k % 10);\n k = Math.trunc(k / 10);\n }\n }\n return res.reverse(); \n}\n// we can devide this question in two parts based on the fact that do we need extra space for the carry see e.g 2\n/**\n * e.g 1: - [1,2,6,3] & k = 516 || No Extra space needed\n * let i = 3 (num.length - 1);\n * step 1: (inside first if block cz 3 >= 0)\n * \t\t\tnum[3] + 516 = 519;\n * \t\t\t519 % 10 = 9;\n * \t\t\tres = [9];\n * \t\t\tk = (519/10) = 51;\n * \t\t\ti-- ==> 2;\n * step 2: (inside first if block cz 2 >= 0)\n * \t\t\tnum[2] + 51 = 57;\n * \t\t\t57 % 10 = 7;\n * \t\t\tres = [9, 7];\n * \t\t\tk = (57/10) = 5;\n * \t\t\ti-- ==> 1;\n * step 3: (inside first if block cz 1 >= 0)\n * \t\t\tnum[1] + 5 = 7;\n * \t\t\t7 % 10 = 7;\n * \t\t\tres = [9, 7, 7];\n * \t\t\tk = (7/10) = 0;\n * \t\t\ti-- ==> 0;\n * step 4: (inside first if block cz 0 >= 0)\n * \t\t\tnum[0] + 0 = 1;\n * \t\t\t1 % 10 = 1;\n * \t\t\tres = [9, 7, 7, 1];\n * \t\t\tk = (1/10) = 0;\n * \t\t\ti-- ==> -1; (first if consition will be false it will * never going to the 2nd if bcz k is already 0)\n * in this case we need to reverse this array to get the result \n * Answer - [9, 7, 7, 1].reverse() => [1, 7, 7, 9]\n */\n\n/**\n * e.g 1: - [9, 9, 9] & k = 1 || Extra space needed\n * let i = 2 (num.length - 1);\n * step 1: (inside first if block cz 2 >= 0)\n * \t\t\tnum[2] + 1 = 10;\n * \t\t\t10 % 10 = 0;\n * \t\t\tres = [0];\n * \t\t\tk = (10/10) = 1;\n * \t\t\ti-- ==> 1;\n * step 2: (inside first if block cz 1 >= 0)\n * \t\t\tnum[1] + 1 = 10;\n * \t\t\t10 % 10 = 0;\n * \t\t\tres = [0, 0];\n * \t\t\tk = (10/10) = 1;\n * \t\t\ti-- ==> 0;\n * step 3: (inside first if block cz 0 >= 0)\n * \t\t\tnum[0] + 1 = 10;\n * \t\t\t10 % 10 = 0;\n * \t\t\tres = [0, 0, 0];\n * \t\t\tk = (10/10) = 1;\n * \t\t\ti-- ==> -1; (loop will break)\n * step 4: (inside SECOND if block cz k is still 1 >= 0 and i = -1)\n * \t\t\t(k value is 1) 1 % 10 = 1;\n * \t\t\tres = [0, 0, 0, 1];\n * \t\t\tk = (1/10) = 0; ( k value finally 0 NO MORE ELEMENTS TO *ADD)\n * Answer - res.reverse() => [1, 0, 0, 0]\n */\n\n``` | 20 | 0 | ['JavaScript'] | 3 |
add-to-array-form-of-integer | [Python3] Improving the Leetcode Solution and Avoiding the Use of 'str', 'int' and 'map' | python3-improving-the-leetcode-solution-ksmap | Notes:\n- Leetcode provided a simple solution, but it is not efficient. K has 5 digits at most, but A can have 10000 elements. This means that the summation mig | dr_sean | NORMAL | 2019-11-26T01:24:45.238618+00:00 | 2019-11-27T19:37:56.419583+00:00 | 3,681 | false | # Notes:\n- Leetcode provided a simple [solution](https://leetcode.com/problems/add-to-array-form-of-integer/solution/), but it is not efficient. K has 5 digits at most, but A can have 10000 elements. This means that the summation might finish after 5 iterations, but the loop will continue for 10000 times! I added a condition to avoid this.\n- I think the purpose of this question is to provide a summation based on elementary school math, and avoid other functions such as \'str\', \'int\' and \'map\'. \n- The Leetcode solution does not work for Python3, but slight changes would make it compatible for both Python/ Python3.\n\n\n# Python/ Python3 code:\n```\n for i in range(len(A) - 1, -1, -1):\n if not K: break\n K, A[i] = divmod(A[i] + K, 10)\n while K:\n K, a = divmod(K, 10)\n A = [a] + A\n return A\n``` | 19 | 1 | ['Python', 'Python3'] | 2 |
add-to-array-form-of-integer | Java easy to understand solution | java-easy-to-understand-solution-by-daij-abzg | \nclass Solution {\n public List<Integer> addToArrayForm(int[] A, int K) {\n LinkedList<Integer> res = new LinkedList<>();\n int carry = 0;\n | daijidj | NORMAL | 2019-02-12T23:38:53.903503+00:00 | 2019-02-12T23:38:53.903547+00:00 | 2,709 | false | ```\nclass Solution {\n public List<Integer> addToArrayForm(int[] A, int K) {\n LinkedList<Integer> res = new LinkedList<>();\n int carry = 0;\n int index = A.length - 1;\n while(K > 0 || index >= 0){\n int curK = K % 10;\n int curA = index >= 0 ? A[index]: 0;\n int curDigitSum = curK + curA + carry;\n int toBeAdded = curDigitSum % 10;\n carry = curDigitSum / 10;\n index --;\n K /= 10;\n res.addFirst(toBeAdded);\n }\n if(carry != 0){\n res.addFirst(1);\n }\n return res;\n }\n}\n``` | 19 | 2 | [] | 2 |
add-to-array-form-of-integer | 4ms (Beats 90.00%)🔥🔥|| Full Explanation✅|| Breadth First Search✅|| C++|| Java|| Python3 | 4ms-beats-9000-full-explanation-breadth-6711j | Intuition :\n- Here we have to add a non-negative integer k to an array of non-negative integers num, where each element in num is between 0 and 9 (inclusive), | N7_BLACKHAT | NORMAL | 2023-02-15T05:18:05.392845+00:00 | 2023-02-15T05:18:05.392899+00:00 | 1,606 | false | # Intuition :\n- Here we have to add a non-negative integer k to an array of non-negative integers num, where each element in num is between 0 and 9 (inclusive), and returning the result as a list of integers.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Explanation to Approach :\n- First, iterate over each element in num and compute the sum of the corresponding digit in num and k. \n- Then store the ones digit of the sum in a new list called ans.\n- If the sum of the two digits is greater than 9, "carrie over" the tens digit to the next iteration of the loop.\n- If k still has remaining digits, they are also added to the ans list. \n- Finally, the resulting list ans is returned.\n# Look at this Example:\n- Let\'s say we have an array num containing the numbers [1, 2, 3, 4] and we want to add the integer k = 567 to it. The expected result would be a list [1, 7, 9, 1].\n# Here\'s how the algorithm works step by step :\n- Starting from the end of the array, we begin by adding the last element of num and k. This gives us 4 + 7 = 11. The ones digit, which is 1, is added to a new list ans and the tens digit, which is 1, is carried over to the next iteration.\n- The next element of num is 3. We add 3 to the carried over tens digit, which gives us 3 + 1 = 4. The ones digit, which is 4, is added to the front of ans, and the tens digit, which is 0, is carried over to the next iteration.\n- The next element of num is 2. We add 2 to the carried over tens digit, which gives us 2 + 0 = 2. The ones digit, which is 2, is added to the front of ans, and the tens digit, which is 0, is carried over to the next iteration.\n- The last element of num is 1. We add 1 to the carried over tens digit, which gives us 1 + 0 = 1. The ones digit, which is 1, is added to the front of ans, and the tens digit, which is 0, is carried over to the next iteration.\n- At this point, we have finished iterating over all elements of num. If there is still a carried over tens digit, it is added to the front of ans. But since the carried over digit is 0, this step doesn\'t do anything in our example.\n- Finally, we return the ans list, which contains the result [1, 7, 9, 1].\n- So, this code adds 567 to the array [1, 2, 3, 4] and returns the list [1, 7, 9, 1].\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity :\n- Time complexity : O(max(N, log(k)))\n```\nReason : Because the algorithm iterates over each element \nin num once and may iterate over the digits of k up to log(k) \ntimes, depending on the size of k. \n```\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(max(N, log(k)))\n```\nReason : Because it creates a new list ans to store the result.\n```\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A\n```\n# Codes [C++ |Java |Python3] \n```C++ []\nclass Solution \n{\n public:\n vector<int> addToArrayForm(vector<int>& num, int k) \n {\n for (int i = num.size() - 1; i >= 0; --i) \n {\n num[i] += k;\n k = num[i] / 10;\n num[i] %= 10;\n }\n while (k > 0) {\n num.insert(begin(num), k % 10);\n k /= 10;\n }\n return num;\n }\n};\n```\n```Java []\nclass Solution \n{\n public List<Integer> addToArrayForm(int[] num, int k) \n {\n List<Integer> ans = new LinkedList<>();\n for (int i = num.length - 1; i >= 0; --i) {\n ans.add(0, (num[i] + k) % 10);\n k = (num[i] + k) / 10;\n }\n while (k > 0) {\n ans.add(0, k % 10);\n k /= 10;\n }\n return ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n for i in reversed(range(len(num))):\n k, num[i] = divmod(num[i] + k, 10)\n\n while k > 0:\n num = [k % 10] + num\n k //= 10\n\n return num\n```\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n\n | 15 | 0 | ['Math', 'Python', 'C++', 'Java', 'Python3'] | 1 |
add-to-array-form-of-integer | JAVA simple solution Array List Beginner friendly | java-simple-solution-array-list-beginner-16is | Runtime: 42 ms, faster than 19.81% of Java online submissions for Add to Array-Form of Integer.\nMemory Usage: 40.4 MB, less than 54.92% of Java online submissi | gautammali_740 | NORMAL | 2021-08-24T06:52:52.892458+00:00 | 2021-08-24T06:52:52.892502+00:00 | 1,822 | false | **Runtime: 42 ms, faster than 19.81% of Java online submissions for Add to Array-Form of Integer.\nMemory Usage: 40.4 MB, less than 54.92% of Java online submissions for Add to Array-Form of Integer.**\n\n\n```\nList<Integer> ans=new ArrayList<>();\n \n for(int i=num.length-1;i>=0;i--){\n \n int n=num[i];\n int sum=n+k;\n int rem=sum%10;\n ans.add(0,rem);\n k=sum/10;\n \n }\n \n while(k>0){\n ans.add(0,k%10);\n k/=10;\n }\n return ans;\n``` | 12 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | Python - One Liner - Better than 88% | python-one-liner-better-than-88-by-mb557-hka3 | Approach:\n1. Convert the list of integers into a single number using join()\n2. Explicitly convert the new string into int and add it with K.\n3. Convert the s | mb557x | NORMAL | 2020-07-10T05:41:26.718236+00:00 | 2020-07-10T05:41:26.718276+00:00 | 1,206 | false | Approach:\n1. Convert the list of integers into a single number using ```join()```\n2. Explicitly convert the new string into int and add it with ```K```.\n3. Convert the sum into string and return it as a list using ```list()```.\n\n```\nclass Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n return (list(str(int("".join(map(str, A))) + K)))\n```\n```\n#Runtime: 304ms\n#Memory Usage: 14.3MB\n```\n | 12 | 2 | ['Python3'] | 4 |
add-to-array-form-of-integer | [JavaScript] Clean and fast solution with explanation.(No reverse) | javascript-clean-and-fast-solution-with-gjnza | js\nvar addToArrayForm = function(A, K) {\n let flag = A.length - 1\n while(K) {\n if(flag < 0) {\n A.unshift(K % 10)\n } else {\ | ray7102ray7102 | NORMAL | 2019-03-19T11:19:10.321240+00:00 | 2019-03-19T11:19:10.321283+00:00 | 1,918 | false | ```js\nvar addToArrayForm = function(A, K) {\n let flag = A.length - 1\n while(K) {\n if(flag < 0) {\n A.unshift(K % 10)\n } else {\n K += A[flag]\n A[flag--] = K % 10\n }\n K = Math.floor(K / 10)\n }\n return A\n}\n```\nExplanation:\n1. Take `K` as a carry.\n2. Use `flag` to point from right to left (from lower to higher digit).\n3. If `flag` less than 0, it means `A` need to insert a new digit to the head of `A`. | 12 | 0 | ['JavaScript'] | 2 |
add-to-array-form-of-integer | Screencast of LeetCode Weekly Contest 123 | screencast-of-leetcode-weekly-contest-12-3k0w | https://www.youtube.com/watch?v=50jJcFYaskQ | cuiaoxiang | NORMAL | 2019-02-10T04:08:04.588689+00:00 | 2019-02-10T04:08:04.588760+00:00 | 1,468 | false | https://www.youtube.com/watch?v=50jJcFYaskQ | 12 | 2 | [] | 4 |
add-to-array-form-of-integer | ✅Java | Easy Solution With Detailed Explanation | java-easy-solution-with-detailed-explana-2xkn | Approach\n Describe your approach to solving the problem. \n- We approach this question just like we add two numbers given that you can add only one-one digits | olifarhaan | NORMAL | 2023-02-15T03:55:29.701630+00:00 | 2023-02-15T13:34:36.262708+00:00 | 2,636 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- We approach this question just like we add two numbers given that you can add only one-one digits at a time.\n- We start iterating to the array from the last of it, & also from the last of k as well.\n- At each iteration, we keep adding the `carry` , `num[i]` , & the last digit of `k` i.e. `k%10` to `digitSum`\n- We add the last digit of `digitSum` to the `list`\n- We keep the rest of the number to `carry`\n\n- After iterating we reverse the `list`. We could also do it without using the `reverse()` method by Using `list.add(0, digitSum%10)`. By doing this the `list` will be in the right order. But this takes more time because after adding the number to the index 0, the rest of the numbers needs to be shifted to the right.\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)` Since we do not have used any extra space. The list that we created is the return type therefore no extra space is used.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Please UPVOTE this if you find it useful\nLet\'s Connect On [LinkedIn OliFarhaan](https://www.linkedin.com/in/olifarhaan/)\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> list= new ArrayList<>();\n int carry=0, digitSum=0;\n int i= num.length-1;\n while(i>=0 || k >0 || carry >0){\n digitSum=carry;\n if(i>=0) digitSum += num[i--];\n if(k>0) digitSum += k%10;\n list.add(digitSum%10);\n k=k/10;\n carry= digitSum/10;\n }\n Collections.reverse(list);\n return list;\n }\n}\n``` | 11 | 0 | ['Array', 'Math', 'Java'] | 2 |
add-to-array-form-of-integer | ✅ For N base characters and beyond | 🔰 O(n) Time and O(n) space❗️ | for-n-base-characters-and-beyond-on-time-bacz | Intuition\nThis problem is similar to problem: 67. Add Binary. You should try and solve that problem first. If you are still confused, see the below solution.\n | hridoy100 | NORMAL | 2023-02-15T05:43:01.380646+00:00 | 2023-02-15T06:29:13.319761+00:00 | 626 | false | # Intuition\nThis problem is similar to problem: [67. Add Binary](https://leetcode.com/problems/add-binary/). You should try and solve that problem first. If you are still confused, see the below solution.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nMy solution to [67. Add Binary](https://leetcode.com/problems/add-binary/) => [https://leetcode.com/problems/add-binary/solutions/3186596/have-you-thought-this-way-beats-100-self-explanatory-code/](https://leetcode.com/problems/add-binary/solutions/3186596/have-you-thought-this-way-beats-100-self-explanatory-code/)\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs you have learned basic summation by hand. You probably have an idea about the **carry**. In this solution we will also need to keep and store **carry** in a variable. You probably start from the right then calculate to the left.\n\nLet\'s see for an example:\n```\nnum = [2,1,5], k = 806\n```\n\n| carry | num1 from k | num2 from num[] | sum | add to list | updated carry |\n|-------|------|------|-----|-----|-----|\n|0 | 6 | 5 | 11 | 1 | 1 |\n|1 | 0 | 1 | 2 | 2 | 0 |\n|0 | 8 | 2 | 10 | 0 | 1 |\n|1 | 0 | 0 | 1 | 1 | 0 |\n\nTo find the last digit from k, we will do k%10. As this is a 10 base number, we need to mod 10. If this was 2 base (binary) or 8 base (octal) number then we need to do k%2 or k%8 respectively.\nAfter doing that, we update k by doing k/10. This means we are erasing the last digit. Again, as it is 10 base number we are using 10. For 2 or 8 base number we will use 2 or 8.\n\nWe iterate the loop of the array. After the iteration is complete, we check if k is 0. If it is not, we further add the values from k.\n\nLastly, an important part is, whether carry is 0 or not. If it is not 0, we must add that to the list.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\nWe are declaring another list to store the output.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code [Java]\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new LinkedList<>();\n int carry = 0;\n for(int i=num.length-1; i>=0; i--){\n int num1 = 0;\n if(k!=0){\n num1 = k%10;\n k/=10;\n }\n int num2 = num[i];\n int sum = carry + num1 + num2;\n carry = sum/10;\n list.add(sum%10);\n }\n while(k!=0){\n int sum = carry + k%10;\n k/=10;\n carry = sum/10;\n list.add(sum%10);\n }\n if(carry!=0){\n list.add(carry);\n }\n Collections.reverse(list);\n return list;\n }\n}\n```\n\n\n | 10 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | 📌📌 C++ || Math || Two Pointer || Faster || Easy To Understand | c-math-two-pointer-faster-easy-to-unders-3s4m | Math\n\n Time Complexity :- O(N)\n\n Space Complexity :- O(Constant)\n\n\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n | __KR_SHANU_IITG | NORMAL | 2023-02-15T03:52:25.143687+00:00 | 2023-02-15T03:52:25.143718+00:00 | 3,001 | false | * ***Math***\n\n* ***Time Complexity :- O(N)***\n\n* ***Space Complexity :- O(Constant)***\n\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n \n int n = num.size();\n \n // convert the k into string\n \n string str = to_string(k);\n \n int m = str.size();\n \n // intitialize i and j\n \n int i = n - 1, j = m - 1;\n \n int carry = 0;\n \n vector<int> res;\n \n // start traversing from right side\n \n while(i >= 0 || j >= 0 || carry)\n {\n // find sum\n \n int sum = 0;\n \n if(i >= 0)\n {\n sum += num[i];\n }\n \n if(j >= 0)\n {\n sum += str[j] - \'0\';\n }\n \n sum += carry;\n \n // update the carry\n \n carry = sum / 10;\n \n // push the digit into res\n \n res.push_back(sum % 10);\n \n // update pointers\n \n i--;\n \n j--;\n }\n \n // reverse the res\n \n reverse(res.begin(), res.end());\n \n return res;\n }\n};\n``` | 10 | 0 | ['Math', 'C', 'C++'] | 1 |
add-to-array-form-of-integer | [Java] 3 different approach || 55ms to 4ms runtime | java-3-different-approach-55ms-to-4ms-ru-ca3p | Hii,\nIntuition :\n\nBASIC IDEA\n1. Basic Idea behind this implementation is to add the num array element one by one with the k\neg:\nnum[] = {1, 2, 3} and k = | kartik04 | NORMAL | 2022-07-11T01:11:01.419597+00:00 | 2022-07-12T21:49:38.572623+00:00 | 999 | false | Hii,\n**Intuition :**\n\nBASIC IDEA\n1. Basic Idea behind this implementation is to add the num array element one by one with the k\neg:\nnum[] = {1, 2, 3} and k = 45;\n\n* \t1st Iteration:\nk += num[len--] --> k = k + num[2] --> k = 45 + 3 --> k = 48\nlist.addFirst(k % 10) --> list.addFirst(48 % 10) --> list.addFirst(8) --> [8]\nk /= 10 --> k = k / 10 --> 48 / 10 --> k = 4\n\n* 2nd Iteration:\nk += num[len--] --> k = k + num[1] --> k = 4 + 2 --> k = 6\nlist.addFirst(k % 10) --> list.addFirst(6 % 10) --> list.addFirst(6) --> [6, 8]\nk /= 10 --> k = k / 10 --> 6 / 10 --> k = 0\n\n* 3rd Iteration:\nk += num[len--] --> k = k + num[0] --> k = 0 + 1 --> k = 1\nlist.addFirst(k % 10) --> list.addFirst(1 % 10) --> list.addFirst(1) --> [1, 6, 8] <--- Desired Output\nk /= 10 --> k = k / 10 --> 1 / 10 --> k = 0\n\n\t// credit @akshayaamar05\n\t\nAt the beginning i was getting **55ms** runtime for submission which was slower than 80% but changing my list it was mitigated to just **4ms** which is faster than ***98%*** submission.\nso, let just look how it was done\n1. First using ArrayLIst we are appending the element at the beginning of ArrayList \n2. taking lot of time process \n3. runtime = 55ms.\n```\npublic List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> list = new ArrayList<Integer>(); \n int len = num.length-1;\n while( len >=0 || k!=0){\n if( len >= 0){\n k += num[len--];\n }\n list.add(0,k % 10); // using .add(int index, E value); method to add element at the beginning of arraylist \n k /= 10;\n } \n return list;\n }\n```\n\nUsing LinkedList\n* using linkedList provide the method addFirst(value) which consumes less time \n* runtime = 7ms.\n* space = 64 MB, less than only 12%.\n```\npublic List<Integer> addToArrayForm(int[] num, int k) {\n LinkedList<Integer> list = new LinkedList<Integer>(); \n int len = num.length-1;\n while( len >=0 || k!=0){\n if( len >= 0){\n k += num[len];\n len--;\n }\n list.addFirst(k % 10); // adding remender to beginning of LinkedList \n k /= 10;\n } \n return list;\n }\n```\n\n\n\n\nAgain using ArrayList but with different approach \n* As we have seen above it is least efficient it is because it has to take some extra time to process the method add(int index, E value)\n* but can avoid this and can achieve most efficient solution for both space and time \n* Runtime = 4ms\n* space = 43 MB lesser than **99.39%**.\n\n```\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> list = new ArrayList<Integer>(); \n int len = num.length-1;\n while( len >=0 || k!=0){\n if( len >= 0){\n k += num[len];\n len--;\n }\n list.add(k % 10); // using normal add method which add element at the end of list. \n k /= 10;\n }\n Collections.reverse(list); // using collections reverse method to reverse our arraylist \n return list;\n }\n```\n\n\nThanks for Reading!\nKeep Grinding!\nPlease Upvote, if you find helpful.\n\n\n | 10 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | Simple Python | simple-python-by-jlepere2-oyvb | \nclass Solution:\n def addToArrayForm(self, A: \'List[int]\', K: \'int\') -> \'List[int]\':\n A[-1] += K\n i = len(A) - 1\n while i > 0 | jlepere2 | NORMAL | 2019-02-10T04:03:26.087533+00:00 | 2019-02-10T04:03:26.087602+00:00 | 1,739 | false | ```\nclass Solution:\n def addToArrayForm(self, A: \'List[int]\', K: \'int\') -> \'List[int]\':\n A[-1] += K\n i = len(A) - 1\n while i > 0 and A[i] > 9:\n A[i-1] += A[i] // 10\n A[i] = A[i] % 10\n i -= 1\n while A[0] > 9:\n A = [A[0] // 10] + A\n A[1] = A[1] % 10\n return A\n``` | 9 | 1 | [] | 1 |
add-to-array-form-of-integer | Easy Javascript solution | easy-javascript-solution-by-kamalbhera-vwjh | \n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n | kamalbhera | NORMAL | 2023-02-15T03:19:04.100660+00:00 | 2023-02-15T09:00:47.546982+00:00 | 2,847 | false | \n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} num\n * @param {number} k\n * @return {number[]}\n */\nvar addToArrayForm = function(num, k) {\n let sum = BigInt(num.join(\'\')) + BigInt(k);\n let convertSum = sum.toString().split(\'\').map((num) => parseInt(num));\n return convertSum;\n};\n``` | 8 | 0 | ['JavaScript'] | 6 |
add-to-array-form-of-integer | 📌📌Python3 || ⚡268 ms, faster than 96.60% of Python3 | python3-268-ms-faster-than-9660-of-pytho-0tq9 | \n\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n if not num:\n return [int(d) for d in str(k)]\n | harshithdshetty | NORMAL | 2023-02-15T02:17:03.578417+00:00 | 2023-02-15T02:17:03.578460+00:00 | 3,153 | false | \n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n if not num:\n return [int(d) for d in str(k)]\n carry = 0\n res = []\n for i in range(len(num)-1, -1, -1):\n total = num[i] + carry + (k % 10)\n carry = total // 10\n res.append(total % 10)\n k //= 10\n while k > 0:\n total = carry + (k % 10)\n carry = total // 10\n res.append(total % 10)\n k //= 10\n if carry > 0:\n res.append(carry)\n return res[::-1]\n```\nThe main idea of the function is to simulate the addition process for two numbers: the input num and the input k. The addition is performed digit by digit, from right to left, while keeping track of the carry from one digit to the next. The function appends each resulting digit to the res list and returns it at the end.\nHere\'s a step by step description of the code:\n\n1. Define a function addToArrayForm that takes in a list of integers num and an integer k, and returns a list of integers.\n1. Check if num is an empty list. If so, convert k to a list of integers and return it.\n1. Initialize variables carry and res to 0 and an empty list, respectively.\n1. Loop over num in reverse order using the range function. At each iteration:\n\t1. \tCalculate the sum of the current digit of num, the corresponding digit of k, and the carry using the modulo operator (%).\n\t1. \tUpdate the carry by dividing the total by 10 using integer division (//).\n\t1. \tAppend the remainder of the total (i.e., total % 10) to res.\n\t1. \tUpdate k by dividing it by 10 using integer division (//).\n1. Loop over k while it is greater than 0. At each iteration:\n\t1. Calculate the sum of the current digit of k and the carry using the modulo operator (%).\n\t1. Update the carry by dividing the total by 10 using integer division (//).\n\t1. Append the remainder of the total (i.e., total % 10) to res.\n\t1. Update k by dividing it by 10 using integer division (//).\n1. If the final carry value is greater than 0, append it to res.\n1. Return the reversed list res. | 8 | 0 | ['Python', 'Python3'] | 1 |
add-to-array-form-of-integer | C# | c-by-leonenko-4xou | \npublic IList<int> AddToArrayForm(int[] A, int K) {\n var i = A.Length - 1;\n var result = new List<int>();\n while(i >= 0 || K > 0) {\n K += ( | leonenko | NORMAL | 2019-02-10T04:20:18.103368+00:00 | 2019-02-10T04:20:18.103426+00:00 | 510 | false | ```\npublic IList<int> AddToArrayForm(int[] A, int K) {\n var i = A.Length - 1;\n var result = new List<int>();\n while(i >= 0 || K > 0) {\n K += (i >= 0 ? A[i--] : 0);\n result.Add((K % 10));\n K /= 10;\n }\n result.Reverse();\n return result;\n}\n``` | 8 | 2 | [] | 0 |
add-to-array-form-of-integer | JAVA EASY Solution WIth EXPLANATION | java-easy-solution-with-explanation-by-d-nhyn | JAVA SOLUTION @DeepakKumar\n# In Case of Any Doubt Feel Free to ASK...\n\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n // | Deepak2002 | NORMAL | 2021-11-02T13:08:26.479529+00:00 | 2021-11-02T13:08:26.479668+00:00 | 811 | false | # JAVA SOLUTION @DeepakKumar\n# In Case of Any Doubt Feel Free to ASK...\n\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n // Create A List\n List<Integer> list = new ArrayList<>();\n // Start from Last index of num Array\n /*\n INDEX -> 0 1 2\n Explanation: let num --> [2,3,2]\n k --> 8947\n ADD num[LAST INDEX] + k --> 2 + 8947 = 8949 --> k\' ADD(9) to LIST\n Now ADD num[1] + (k\' % 10) --> 3 + 894 = 897 --> k\' ADD(7) to LIST\n Now ADD num[0] + (k\' % 10) --> 2 + 89 = 91 --> k\' ADD(1) to LIST\n k = k\' % 10 = 9\n At the End of the loop k != 0 So \n Now ADD DIGITS of k to list FROM the END --> ADD(9) to List\n Now k is 0 so END while Loop\n \n At this point we have List as --> [9,7,1,9] --> **Here NOTE that it is the REQUIRED ANS BUT **\n\t IN REVERSE ORDER\n --> So, now REVERSE the LIST \n --> At the END return the Required List \n */\n for(int i=num.length-1 ; i>=0;i--) {\n int sum = num[i] + k;\n list.add(sum % 10);\n k = sum/ 10; \n }\n // if After Adding k in the Number k is not ZERO then do this\n while(k > 0){\n list.add(k%10);\n k /= 10;\n }\n // Now Reverse the LIST\n Collections.reverse(list);\n // AT the end Return the list\n return list;\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | A Simple Java Solution | a-simple-java-solution-by-praneeth003-o1zn | \n\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n for (in | Praneeth003 | NORMAL | 2021-08-27T15:07:15.006451+00:00 | 2021-08-27T15:07:15.006502+00:00 | 1,018 | false | \n\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n for (int i = num.length - 1; i >= 0 ; i--) {\n arr.add((num[i] + k) % 10);\n k = (num[i] + k) / 10;\n }\n while (k>0){\n arr.add(k % 10);\n k = k /10;\n }\n Collections.reverse(arr);\n return arr;\n }\n}\n```\n\nComment down if needed more clarity. | 7 | 1 | ['Java'] | 1 |
add-to-array-form-of-integer | Python3 One Line | python3-one-line-by-jimmyyentran-zdd1 | A = [1,2,0,0], K = 34\n[1,2,0,0] -> "1200" -> 1200 -> add K -> 1234 -> "1234" -> [1,2,3,4]\npython\nclass Solution:\n def addToArrayForm(self, A: \'List[int] | jimmyyentran | NORMAL | 2019-02-10T04:11:14.078698+00:00 | 2019-02-10T04:11:14.078763+00:00 | 787 | false | A = [1,2,0,0], K = 34\n[1,2,0,0] -> "1200" -> 1200 -> add K -> 1234 -> "1234" -> [1,2,3,4]\n```python\nclass Solution:\n def addToArrayForm(self, A: \'List[int]\', K: \'int\') -> \'List[int]\':\n return [int(s) for s in str(int(\'\'.join(str(x) for x in A)) + K)]\n``` | 7 | 1 | [] | 1 |
add-to-array-form-of-integer | ✔C++|Very Easy | Beats 100% | O(n) |✔ | cvery-easy-beats-100-on-by-xahoor72-uddq | Intuition\n Describe your first thoughts on how to solve this problem. \nSimply just transform k into an array for easy traversal then just take care of carry a | Xahoor72 | NORMAL | 2023-02-15T06:07:14.875523+00:00 | 2023-02-15T06:32:49.700727+00:00 | 4,321 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply just transform k into an array for easy traversal then just take care of carry and take the sum of nums vector and kth vector .\n- We can avoid using the vector for k by just taking directly elements from k .\n- Below are given the two implementations :\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(max(n,logK))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(max(n,logK))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& arr, int k) {\n vector<int>ans;\n vector<int>v;\n while(k>0){\n v.push_back(k%10);\n k/=10;\n }\n reverse(begin(v),end(v));\n int n=arr.size();\n int carry=0;\n int i=n-1,j=v.size()-1;\n while(i>=0 or j>=0){\n int sum=carry;\n if(i>=0)sum+=arr[i--];\n if(j>=0)sum+=v[j--];\n carry=sum/10;\n ans.push_back(sum%10);\n }\n if(carry)\n ans.push_back(carry);\n reverse(begin(ans),end(ans));\n return ans;\n }\n};\n```\n**Wihtout using a vector for k**\n```\nvector<int> addToArrayForm(vector<int>& arr, int k) {\n vector<int>ans;\n int i=arr.size()-1;\n int carry=0;\n while(k>0 or i>=0){\n int sum=carry;\n if(i>=0)sum+=arr[i--];\n sum+=k%10;\n carry=sum/10;\n k/=10;\n ans.push_back(sum%10);\n }\n if(carry)ans.push_back(carry);\n reverse(ans.begin(),ans.end());\n return ans;\n }\n``` | 6 | 0 | ['Array', 'Math', 'Number Theory', 'C++'] | 0 |
add-to-array-form-of-integer | Beginner friendly [JavaScript/Python] solution | beginner-friendly-javascriptpython-solut-myx6 | \njavascript []\nvar addToArrayForm = function(num, k) {\n let res = [], i=num.length\n while(i-- > 0 || k){\n if(i >= 0) k += num[i];\n re | HimanshuBhoir | NORMAL | 2022-08-12T14:32:05.307111+00:00 | 2022-12-19T12:57:40.562113+00:00 | 1,284 | false | \n```javascript []\nvar addToArrayForm = function(num, k) {\n let res = [], i=num.length\n while(i-- > 0 || k){\n if(i >= 0) k += num[i];\n res.unshift(k%10)\n k = Math.floor(k/10)\n }\n return res\n};\n```\n\n``` python []\nclass Solution(object):\n def addToArrayForm(self, num, k):\n res = [] \n i=len(num)-1\n while i >= 0 or k:\n if i >= 0:\n k += num[i]\n res.insert(0, k%10)\n k = k/10\n i -= 1\n return res\n``` | 6 | 0 | ['Python', 'JavaScript'] | 0 |
add-to-array-form-of-integer | C++: Faster than 91% of C++ | c-faster-than-91-of-c-by-vmk1802-tqb2 | \nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int> &A, int K)\n {\n int i, size = A.size();\n\n for (i = size - 1; i >= 0 | vmk1802 | NORMAL | 2020-12-01T15:07:46.165232+00:00 | 2020-12-22T12:13:42.988707+00:00 | 1,231 | false | ```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int> &A, int K)\n {\n int i, size = A.size();\n\n for (i = size - 1; i >= 0 && K != 0; i--)\n {\n K = K + A[i];\n A[i] = K % 10;\n K = K / 10;\n }\n while (K != 0)\n {\n A.insert(A.begin(), K % 10);\n K = K / 10;\n }\n return A;\n }\n};\n``` | 6 | 0 | ['C', 'C++'] | 0 |
add-to-array-form-of-integer | C++ Reverse | c-reverse-by-votrubac-b7eb | Reverse the string first to simplify things. Then add numbers left to rigth, and mind the overflow.\n\nIf needed, add an extra character to the end of the strin | votrubac | NORMAL | 2019-02-10T04:07:58.463777+00:00 | 2019-02-10T04:07:58.463817+00:00 | 934 | false | Reverse the string first to simplify things. Then add numbers left to rigth, and mind the overflow.\n\nIf needed, add an extra character to the end of the string. Since the string is reversed, adding a character does not require shifting the whole string.\n\nIn the end, reverse the string back.\n```\nvector<int> addToArrayForm(vector<int>& A, int K) {\n reverse(begin(A), end(A));\n for (size_t i = 0; K > 0; K /= 10, ++i) {\n A.resize(max(i + 1, A.size()));\n if ((A[i] += K % 10) >= 10) {\n A[i] -= 10;\n K += 10;\n }\n }\n reverse(begin(A), end(A));\n return A;\n}\n``` | 6 | 2 | [] | 0 |
add-to-array-form-of-integer | JAVA || Beats 98% | java-beats-98-by-tamannannaaaa-xn1m | \n# Code\njava []\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> result=new ArrayList<>();\n int n | tamannannaaaa | NORMAL | 2024-09-05T20:52:12.323119+00:00 | 2024-09-05T20:52:12.323148+00:00 | 369 | false | \n# Code\n```java []\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> result=new ArrayList<>();\n int n=num.length;\n\n for(int i=n-1;i>=0;i--){\n k+=num[i];\n result.add(k%10); \n k/=10; \n }\n while(k>0){\n result.add(k%10);\n k/=10;\n }\n Collections.reverse(result);\n return result;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | [Python] - Clean & Simple Solution | python-clean-simple-solution-by-yash_vis-5flc | For Time Complexity we can say O(n),\nand for space O(1). \n\n# Code\n\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n | yash_visavadia | NORMAL | 2023-02-15T18:44:28.578027+00:00 | 2023-02-15T18:48:06.972077+00:00 | 562 | false | - For Time Complexity we can say O(n),\nand for space O(1). \n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n n = 0\n for i in num:\n n = n * 10 + i\n \n n = n + k\n num = []\n\n while n != 0:\n num.append(n % 10)\n n //= 10\n \n return num[::-1]\n```\n\n## One Liner\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return [int(i) for i in str(int(\'\'.join(map(str,num))) + k)]\n\n``` | 5 | 0 | ['Python3'] | 0 |
add-to-array-form-of-integer | [Java] array solution like in school | java-array-solution-like-in-school-by-ol-oj4e | \nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n int plus = 0;\n LinkedList<Integer>res = new LinkedList<>();\n | olsh | NORMAL | 2023-02-15T15:10:13.073589+00:00 | 2023-02-15T15:10:13.073616+00:00 | 42 | false | ```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n int plus = 0;\n LinkedList<Integer>res = new LinkedList<>();\n for (int i=0;i<num.length || k>0;){\n int currentDigitK = k%10;\n int currenntDigitRes = ((i<num.length)?num[num.length-1-i]:0) + currentDigitK+plus;\n plus=currenntDigitRes>9?1:0; \n res.addFirst(currenntDigitRes%10);\n i++;\n k/=10;\n }\n if (plus>0)res.addFirst(plus);\n return res;\n }\n}\n``` | 5 | 0 | [] | 0 |
add-to-array-form-of-integer | JAVA SOLUTION || Easy peasy lemon squeezy😊 || SIMPLE | java-solution-easy-peasy-lemon-squeezy-s-tsg4 | \n\n# Code\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayList<>();\n int i = nu | Sauravmehta | NORMAL | 2023-02-15T11:16:18.424142+00:00 | 2023-02-15T11:16:18.424170+00:00 | 525 | false | \n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayList<>();\n int i = num.length-1;\n int carry = 0;\n while(i >= 0){\n int val = num[i] + (k % 10) + carry;\n if(val > 9){\n list.add ( val % 10);\n val = val/10;\n carry = val;\n }\n else{\n list.add( val);\n carry = 0;\n }\n i--;\n k=k/10;\n }\n\n if(i >=0 ){\n while(i >= 0){\n list.add(num[i]);\n i--;\n }\n }\n if(k != 0){\n while(k>0){\n int val = (k % 10) + carry;\n if(val > 9){\n list.add ( val % 10);\n val = val/10;\n carry = val;\n }\n else{\n list.add( val);\n carry = 0;\n }\n k = k/10;\n }\n }\n if(carry !=0 ) list.add(carry);\n Collections.reverse(list);\n return list;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | Java Solution || The Hard way | java-solution-the-hard-way-by-gau5tam-2741 | Please UPVOTE if you like my solution!\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayL | gau5tam | NORMAL | 2023-02-15T09:48:20.781383+00:00 | 2023-02-15T09:48:20.781418+00:00 | 211 | false | Please **UPVOTE** if you like my solution!\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayList<>();\n String n = "";\n for(int i = num.length-1;i>=0;i--){\n n += String.valueOf(num[i]); \n }\n StringBuilder sb = new StringBuilder(String.valueOf(k));\n String s = sb.reverse().toString();\n\n int carry = 0;\n int sum = 0;\n for(int i = 0,j = 0;i<n.length() || j<s.length();i++,j++){\n \n if(i >= n.length()){\n sum = (s.charAt(j)-\'0\') + carry;\n carry = 0;\n }\n else if(j >= s.length()){\n sum = (n.charAt(i)-\'0\') + carry;\n carry = 0;\n }\n else{\n sum = (n.charAt(i)-\'0\') + (s.charAt(j)-\'0\') + carry;\n carry = 0;\n }\n if(sum>=10){\n list.add(sum%10);\n carry = sum/10;\n }\n else if(i == n.length()-1 && j >= s.length() && sum >= 10){\n list.add(sum%10);\n list.add(sum/10);\n }\n else if(i >= n.length() && j == s.length()-1 && sum >= 10){\n list.add(sum%10);\n list.add(sum/10);\n }\n else if(i == n.length()-1 && j == s.length()-1 && sum >= 10){\n list.add(sum%10);\n list.add(sum/10);\n }\n else{\n list.add(sum);\n } \n }\n if(carry != 0){\n list.add(1);\n }\n \n Collections.reverse(list);\n return list;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | C++ ||Begineer Friendly|| Easy-Understanding|| Video solution | c-begineer-friendly-easy-understanding-v-uoya | Intuition\n Describe your first thoughts on how to solve this problem. \nC++ Clear Explaination ,Please support if you find it usefull. Can give me feedback in | with_Sky_04 | NORMAL | 2023-02-15T05:46:18.333761+00:00 | 2023-02-15T05:46:18.333791+00:00 | 1,508 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**C++ Clear Explaination ,Please support if you find it usefull. Can give me feedback in comment for improvement.,will be very thankfull.**\nhttps://www.youtube.com/watch?v=qWmANiGB00I/\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n\n for(int i=num.size()-1;i>=0;i--){\n int temp = num[i]+k;\n // value to store .\n num[i] = temp%10;\n k=temp/10; // carry.\n }\n // if k>0 that means we need to insert in front.\n while(k>0){\n num.insert(num.begin(),k%10);\n k=k/10;\n }\n\n return num;\n\n\n }\n};\n``` | 5 | 0 | ['Array', 'Math', 'C', 'C++', 'Java'] | 0 |
add-to-array-form-of-integer | 🗓️ Daily LeetCoding Challenge February, Day 15 | daily-leetcoding-challenge-february-day-90c46 | This problem is the Daily LeetCoding Challenge for February, Day 15. Feel free to share anything related to this problem here! You can ask questions, discuss wh | leetcode | OFFICIAL | 2023-02-15T00:00:16.794556+00:00 | 2023-02-15T00:00:16.794623+00:00 | 4,257 | false | This problem is the Daily LeetCoding Challenge for February, Day 15.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/add-to-array-form-of-integer/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain this 1 approach in the official solution</summary>
**Approach 1:** Schoolbook Addition
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 5 | 0 | [] | 26 |
add-to-array-form-of-integer | ✅ EASY & BETTER C++ Solution | EXPLAINED | IN-PLACE | O(n) | easy-better-c-solution-explained-in-plac-m26h | Algorithm:\n1. Traversing the vector array from last and continuously adding the last element of integer \'K\'\n\ta. Adding k to num[i]\n\tb. Updating k by num[ | ke4e | NORMAL | 2022-07-12T08:53:59.170867+00:00 | 2022-07-12T08:53:59.170913+00:00 | 508 | false | Algorithm:\n1. Traversing the vector array from last and continuously adding the last element of integer \'K\'\n\ta. Adding k to num[i]\n\tb. Updating k by num[i]/10\n\tb. Updating num[i] by num[i]%10 \n2. If any carry left, it will be inserted at start of the vector array num\n3. Return the array.\n\nTime Complexity: O(n)\nSpace Complexity: O(1)\n\nThanks for reading, If you like it, please upvote \u2B06\uFE0F and help me gain good reputation.\n\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n // Peforming element wise sum\n for (int i=num.size()-1; i>=0 && k>0; i--) {\n num[i]+=k;\n k=num[i]/10;\n num[i]%=10;\n }\n \n // if carry left, insert it in vector in front\n while(k>0) {\n num.insert(num.begin(), k%10);\n k/=10;\n }\n \n return num;\n }\n};\n``` | 5 | 0 | ['C'] | 0 |
add-to-array-form-of-integer | Java Solution | java-solution-by-ishikaroy0100-95nb | ```\nclass Solution {\n public List addToArrayForm(int[] num, int k) {\n List list=new ArrayList<>();\n int i=num.length-1;\n while(i>=0 | ishikaroy0100 | NORMAL | 2022-01-25T07:00:16.940666+00:00 | 2022-01-25T07:00:16.940704+00:00 | 620 | false | ```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list=new ArrayList<>();\n int i=num.length-1;\n while(i>=0 || k>0){\n if(i>=0)\n k=k+num[i];\n list.add(k%10);\n k/=10;\n i--;\n }\n Collections.reverse(list);\n return list;\n }\n} | 5 | 0 | ['Java'] | 2 |
add-to-array-form-of-integer | Easiest solution | O(n) | Amazon |Facebook asked | 10 Lines of code | easiest-solution-on-amazon-facebook-aske-ca3w | If you like my approach please do upvote!\n\nIn this we have converted a number to string so that we can add it\'s corresponding values easily!\n\nclass Solutio | astha77 | NORMAL | 2021-01-12T12:21:00.881480+00:00 | 2021-01-12T12:31:16.002531+00:00 | 487 | false | If you like my approach please do upvote!\n\nIn this we have converted a number to string so that we can add it\'s corresponding values easily!\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& A, int K) {\n vector<int>v;\n string p=to_string(K);\n int l1=A.size()-1;\n int l2=p.size()-1;\n int carry=0;\n int i=0;\n while(l1>=0 || l2>=0){\n \n int sum=carry;\n //here sum=sum+carry would be same as this s have written it like this only\n if(l1>=0){\n sum=sum+A[l1--];\n }\n if(l2>=0){\n sum=sum+p[l2--]-\'0\';\n }\n v.push_back(sum%10);\n carry=sum/10;\n \n }\n if(carry>0){\n v.push_back(carry);\n }\n reverse(v.begin(),v.end());\n \n return v;\n }\n};\n```\n | 5 | 1 | ['String', 'C'] | 0 |
add-to-array-form-of-integer | JavaScript Solution | javascript-solution-by-deadication-vxqi | \nvar addToArrayForm = function(A, K) {\n // i = current index of array A\n // c = carry\n // k = current least significant digit of K\n // a = curr | Deadication | NORMAL | 2020-04-10T17:10:12.850571+00:00 | 2020-04-10T17:12:56.111679+00:00 | 1,088 | false | ```\nvar addToArrayForm = function(A, K) {\n // i = current index of array A\n // c = carry\n // k = current least significant digit of K\n // a = current least significant digit of A\n // d = current digit to push\n \n const n = A.length\n const temp = []\n let i = n - 1\n let c = 0\n \n while (i >= 0 || K > 0) {\n let k = K % 10\n let a = i < 0 ? 0 : A[i]\n let s = k + a + c\n let d = s % 10\n temp.push(d)\n c = s > 9 ? 1 : 0\n K = Math.floor(K / 10)\n i--\n }\n\n if (c == 1) temp.push(c)\n \n return temp.reverse()\n};\n``` | 5 | 1 | ['JavaScript'] | 1 |
add-to-array-form-of-integer | 1 line lazy javascript solution | 1-line-lazy-javascript-solution-by-daima-v32t | \n156 / 156 test cases passed.\nStatus: Accepted\nRuntime: 176 ms\nMemory Usage: 42.1 MB\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {numbe | daimant | NORMAL | 2020-04-03T09:09:24.546774+00:00 | 2020-04-03T09:09:24.546809+00:00 | 650 | false | ```\n156 / 156 test cases passed.\nStatus: Accepted\nRuntime: 176 ms\nMemory Usage: 42.1 MB\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number[]}\n */\nvar addToArrayForm = function(A, K) {\n return [...(BigInt(A.join(\'\')) + BigInt(K) + \'\')];\n};\n``` | 5 | 0 | ['JavaScript'] | 0 |
add-to-array-form-of-integer | Accepted Python3: One Liner using map() | accepted-python3-one-liner-using-map-by-j4yk1 | \nclass Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n return list(map(int, list(str(int(\'\'.join(map(str, A))) + K))))\n | i-i | NORMAL | 2019-12-08T18:58:41.898029+00:00 | 2019-12-08T18:58:41.898085+00:00 | 684 | false | ```\nclass Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n return list(map(int, list(str(int(\'\'.join(map(str, A))) + K))))\n``` | 5 | 0 | ['Python', 'Python3'] | 1 |
add-to-array-form-of-integer | ✔️C++ SOLUTION✔️ | c-solution-by-2005115-c9z1 | PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand | 2005115 | NORMAL | 2023-11-07T17:43:12.135997+00:00 | 2023-11-07T17:43:12.136023+00:00 | 273 | false | # **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/pratay_nandy/]()**\n# Approach\nThe provided C++ code is an updated version of the previous code and defines a class "Solution" with a public member function "addToArrayForm." This function takes a vector of integers `nums` and an integer `k` as input and aims to add the integer `k` to the number represented by the elements of the `nums` vector and return the result as a new vector. This updated code addresses memory usage by minimizing the need for an extra vector and optimization for better clarity.\n\nHere\'s the approach used in this code:\n\n1. Initialize an empty vector `ans` to store the result.\n\n2. Initialize two variables, `i` and `carry`. `i` is set to the index of the last element in the `nums` vector, and `carry` is initially set to 0.\n\n3. The code uses a while loop to perform the addition. It handles three cases:\n\n a. **Both number and array of the same size:** While `i` is greater than or equal to 0 and `k` is greater than 0, the code extracts the least significant digit (rightmost digit) of `k` and the corresponding digit from the `nums` array, adds them together along with the carry from the previous operation, calculates the new carry and the sum. The sum is added to the `ans` vector, and `i` and `k` are decremented.\n\n b. **When the array is bigger than the number:** If `i` is still greater than or equal to 0 after the first loop, it means the array is longer than the number. In this case, the code adds the elements of `nums` and the carry, calculates the new carry, and adds the result to the `ans` vector.\n\n c. **When the number is bigger than the array:** If `k` is still greater than 0 after the first loop, it means the number is longer than the array. The code extracts the least significant digit of `k`, adds it to the carry, calculates the new carry, and adds the result to the `ans` vector.\n\n4. After all the additions, if there is still a carry, it is added as the most significant digit to the `ans` vector in a separate loop.\n\n5. Finally, the `ans` vector is reversed to ensure the least significant digit is at the beginning, and it is returned as the result.\n\nThe code effectively performs the addition of the integer `k` to the number represented by the `nums` vector and returns the result as a new vector, taking into account different scenarios involving array and number sizes. This updated code is designed to optimize memory usage.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& nums, int k) {\n vector<int>ans;\n int i = nums.size()-1; \n int carry = 0;\n // both number and array of same size\n while(i>=0 && k>0)\n {\n int left = k%10;\n k = k/10;\n int sum = nums[i] + left + carry;\n carry = sum / 10;\n sum=sum % 10; \n ans.push_back(sum);\n i--; \n }\n // when array is big\n while(i>=0)\n {\n int sum = nums[i] + carry;\n carry = sum / 10;\n sum=sum % 10; \n ans.push_back(sum);\n i--; \n }\n // when number is big\n while(k>0)\n {\n int left = k%10;\n k = k/10;\n int sum = left + carry;\n carry = sum / 10;\n sum=sum % 10; \n ans.push_back(sum);\n }\n while(carry!=0)\n {\n int sum = carry;\n carry = sum / 10;\n sum=sum % 10; \n ans.push_back(sum);\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Math', 'C++'] | 0 |
add-to-array-form-of-integer | Easy Java Solution || Using stack | easy-java-solution-using-stack-by-apoora-foa0 | Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem, you can start by converting the array num into an integer, then a | apooravsingh38 | NORMAL | 2023-02-15T08:41:31.847130+00:00 | 2023-02-15T08:41:31.847163+00:00 | 1,048 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem, you can start by converting the array num into an integer, then add k to it, and finally convert the result back into an array. However, since the constraints are quite large, you need to be careful about the implementation to avoid integer overflow.\n\nOne way to avoid integer overflow is to add k to the least significant digit of num, then compute the carry and propagate it to the more significant digits until there is no more carry. To convert the result back into an array, you can use a stack to store the digits in reverse order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Initialize a stack to store the digits of the result in reverse order, and set the carry to k.\nIterate over the digits of the input array num from right to left, adding each digit to the carry and updating the carry accordingly. If the input array has more digits than k, the remaining digits are effectively treated as zeros.\nAfter processing all the digits of num, or if there is still a carry, continue the iteration by adding the carry to the next digit (which may be zero), and updating the carry accordingly.\nCompute the least significant digit of the result by taking the remainder of the sum modulo 10, and push it onto the stack.\nDivide the sum by 10 to update the carry, and repeat the process for the next digit.\nAfter processing all the digits, the stack contains the digits of the result in reverse order, so we create a new list and pop the digits from the stack one by one, adding them to the list.\nReturn the list as the final result.\n\n\n# Complexity\n- Time complexity:O(max(N, log K))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(max(N, log K))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n // Initialize a stack to store the digits of the result in reverse order, and set the carry to k.\n Stack<Integer> stack = new Stack<>();\n int carry = k;\n \n // Iterate over the digits of the input array num from right to left, adding each digit to the carry and updating the carry accordingly.\n int i = num.length - 1;\n while (i >= 0 || carry > 0) {\n if (i >= 0) {\n carry += num[i];\n }\n \n // Compute the least significant digit of the result by taking the remainder of the sum modulo 10, and push it onto the stack.\n stack.push(carry % 10);\n \n // Divide the sum by 10 to update the carry, and repeat the process for the next digit.\n carry /= 10;\n i--;\n }\n \n // Create a new list to store the digits of the result in the correct order, and pop the digits from the stack one by one, adding them to the list.\n List<Integer> result = new ArrayList<>();\n while (!stack.isEmpty()) {\n result.add(stack.pop());\n }\n \n // Return the list as the final result.\n return result;\n }\n}\n\n``` | 4 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | ✅ [Java/C++] 100% Solution using Math (Add to Array-Form of Integer) | javac-100-solution-using-math-add-to-arr-obyn | Complexity\n- Time complexity: O(max(n,m)) \n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(max(n,m))\n Add your space complexity here, e.g | arnavsharma2711 | NORMAL | 2023-02-15T05:27:27.885959+00:00 | 2023-02-15T05:27:27.886011+00:00 | 173 | false | # Complexity\n- Time complexity: $$O(max(n,m))$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(max(n,m))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n*where n is size of num vector and m is number of digits in k.*\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int> ans;\n int i=num.size();\n while(i || k!=0)\n {\n if(i>0)\n k+=num[--i];\n\n ans.push_back(k%10);\n k/=10;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> ans = new ArrayList<>();\n int i=num.length;\n while(i>0 || k!=0)\n {\n if(i>0)\n k+=num[--i];\n\n ans.add(k%10);\n k/=10;\n }\n Collections.reverse(ans);\n return ans;\n }\n}\n``` | 4 | 0 | ['Math', 'C++', 'Java'] | 0 |
add-to-array-form-of-integer | Golang short and simple solution | golang-short-and-simple-solution-by-traf-r0l0 | Complexity\n- Time complexity: O(n)\n- Space complexity: O(1) - if we don\'t count additional elements produced by k. But it\'s limited to 4 as k <= 10^4\n\n\n# | traffiknewmail | NORMAL | 2023-02-15T03:16:24.879787+00:00 | 2023-02-15T03:20:34.134599+00:00 | 365 | false | # Complexity\n- Time complexity: O(n)\n- Space complexity: O(1) - if we don\'t count additional elements produced by k. But it\'s limited to 4 as k <= 10^4\n\n\n# Code\n```\nfunc addToArrayForm(num []int, k int) []int {\n i := 1\n for k > 0 {\n if len(num) >= i {\n k += num[len(num)-i]\n num[len(num)-i] = k % 10\n } else {\n num = append([]int{k % 10}, num...)\n }\n i++\n k = k / 10\n }\n return num\n}\n``` | 4 | 0 | ['Go'] | 0 |
add-to-array-form-of-integer | C++✅✅ | 0ms Faster Solution⏳ | O(1) Space Complexity | Clean and Understandable😇 | c-0ms-faster-solution-o1-space-complexit-dkbz | Code\n# PLEASE DO UPVOTE !\nCONNECT WITH ME ON LINKEDIN : https://www.linkedin.com/in/kunal-shaw-/\n\nclass Solution {\npublic:\n vector<int> addToArrayForm( | kunal0612 | NORMAL | 2023-02-15T02:49:20.873963+00:00 | 2023-02-15T02:49:20.874008+00:00 | 2,347 | false | # Code\n# **PLEASE DO UPVOTE !**\n**CONNECT WITH ME ON LINKEDIN : https://www.linkedin.com/in/kunal-shaw-/**\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int n=num.size();\n int c=0;\n int i;\n for(i=n-1;i>=0 or k>0;i--){\n int r=k%10;\n k/=10;\n if(i>=0){\n int res=num[i]+r+c;\n num[i]=res%10;\n c=res/10;\n }\n else{\n int res=r+c;\n num.insert(num.begin(),res%10);\n c=res/10;\n }\n\n }\n if(c>0){\n num.insert(num.begin(),c);\n }\n return num;\n }\n};\n```\n | 4 | 0 | ['Math', 'C++'] | 2 |
add-to-array-form-of-integer | One Liner | parseInt Substitute | one-liner-parseint-substitute-by-aniketc-eyg5 | 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 | aniketcodes | NORMAL | 2023-02-15T02:42:40.313909+00:00 | 2023-02-15T02:42:40.313945+00:00 | 1,151 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} num\n * @param {number} k\n * @return {number[]}\n */\nvar addToArrayForm = function(num, k) {\n return [...(BigInt(num.join(""))+BigInt(k)).toString()]\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
add-to-array-form-of-integer | Java || BigInteger || Easy to UnderStand | java-biginteger-easy-to-understand-by-ma-ew1o | \nimport java.math.BigInteger;\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n String s="";\n for(int i:num){\n | Manoj_07 | NORMAL | 2023-01-30T17:47:25.066249+00:00 | 2023-01-30T17:47:25.066292+00:00 | 745 | false | ```\nimport java.math.BigInteger;\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n String s="";\n for(int i:num){\n s+=i;\n }\n String kk=k+"";\n List<Integer> al=new ArrayList<>();\n BigInteger a=new BigInteger(s);\n BigInteger b=new BigInteger(kk);\n BigInteger c=a.add(b);\n String str=c.toString();\n for(char ch:str.toCharArray()){\n al.add(ch-\'0\');\n }\n return al;\n }\n}\n``` | 4 | 0 | [] | 3 |
add-to-array-form-of-integer | Java simple solution |faster than 97%| | java-simple-solution-faster-than-97-by-u-0v8r | class Solution {\n public List addToArrayForm(int[] num, int k) {\n\t\n int n = num.length;\n int i = n-1;\n List sol = new ArrayList<>( | Ujjwall19 | NORMAL | 2022-09-05T19:31:56.421697+00:00 | 2022-09-05T19:31:56.421741+00:00 | 1,266 | false | class Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n\t\n int n = num.length;\n int i = n-1;\n List<Integer> sol = new ArrayList<>();\n while(i >= 0 || k > 0) { \n if(i >= 0) {\n sol.add((num[i] + k) % 10);\n k = (num[i] + k) / 10;\n } else { \n sol.add(k % 10);\n k = k / 10;\n }\n i--;\n }\n Collections.reverse(sol);\n return sol;\n }\n} | 4 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | ✔️Python, C++,Java|| Beginner level ||As Simple As U Think||Simple-Short-Solution✔️ | python-cjava-beginner-level-as-simple-as-4ddm | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n___\n__\nQ | Anos | NORMAL | 2022-08-26T11:24:47.123749+00:00 | 2022-08-26T11:24:47.123795+00:00 | 779 | false | ***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q989. Add to Array-Form of Integer***\nThe **array-form** of an integer num is an array representing its digits in left to right order.\n\n* `For example, for num = 1321, the array form is [1,3,2,1].`\n\nGiven num, the **array-form** of an integer, and an integer k`, return the `**array-form** of the integer `num + k`\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n s=\'\'.join(map(str,num))\n a=int(s)+k\n return [int(i) for i in str(a)]\n```\n**Runtime:** 662 ms\t\n**Memory Usage:** 13.9 MB\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num ,int k) {\n List<Integer> res = new LinkedList<>();\n for (int i = num.length - 1; i >= 0; --i) \n {\n res.add(0, (num[i] + k) % 10);\n k = (num[i] + k) / 10;\n }\n while (k > 0) {\n res.add(0, k % 10);\n k /= 10;\n }\n return res;\n }\n}\n```\n**Runtime:** 11 ms\t\t\n**Memory Usage:** 62.8 MB\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int l=num.size()-1;\n for(int i=l;i>=0&&k>0;--i)\n {\n num[i]=num[i]+k;\n k=num[i]/10;\n num[i]=num[i]%10;\n }\n while(k>0)\n {\n num.insert(num.begin(),k%10);\n k/=10;\n }\n return num;\n }\n};\n```\n**Runtime:** 11 ms\t\n**Memory Usage:** 62.3 MB\t\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 4 | 0 | ['C', 'Python', 'Java'] | 0 |
add-to-array-form-of-integer | C solution, 98 ms, 15.9 MB | c-solution-98-ms-159-mb-by-uneducatedper-jeyy | \n\n\nint* addToArrayForm(int* num, int numSize, int k, int* returnSize){\n int car = 0; int* returnNum;\n *returnSize = numSize;\n \n for (int i = | uneducatedPerson | NORMAL | 2022-08-06T01:00:12.087454+00:00 | 2022-08-06T01:11:03.418221+00:00 | 393 | false | \n\n```\nint* addToArrayForm(int* num, int numSize, int k, int* returnSize){\n int car = 0; int* returnNum;\n *returnSize = numSize;\n \n for (int i = numSize - 1; i > -1; i--)\n {\n num[i] += ((k % 10) + car);\n k /= 10;\n \n if (num[i] > 9)\n {\n car = 1;\n num[i] %= 10;\n }\n else car = 0;\n }\n \n\t// i.e. if k.len > num.len and/or (num + k).len > num.len\n if (k || car)\n {\n k += car;\n int nlen = ((k) ? log10(k) + 1 : 0);\n *returnSize += nlen;\n returnNum = (int*) malloc(sizeof(int) * (*returnSize));\n \n for (int i = nlen - 1; i > -1; i--) \n {\n returnNum[i] = k % 10;\n k /= 10;\n }\n for (int i = nlen; i < (*returnSize); i++) returnNum[i] = num[i - nlen];\n }\n else\n {\n returnNum = (int*) malloc(sizeof(int) * numSize); \n for (int i = 0; i < numSize; i++) returnNum[i] = num[i];\n }\n \n return returnNum;\n}\n``` | 4 | 0 | ['Array', 'C'] | 0 |
add-to-array-form-of-integer | simple C++ code with explanation || comments added | simple-c-code-with-explanation-comments-gr43m | \nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int>ans;\n int carry=0;\n \n int i=num.size()-1 | _RaviPratap_ | NORMAL | 2022-07-17T07:25:39.338352+00:00 | 2022-07-17T07:25:39.338402+00:00 | 600 | false | ```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int>ans;\n int carry=0;\n \n int i=num.size()-1;\n while(i>=0 || carry>0 || k!=0 )\n {\n if(k!=0) // here we are adding last digit of k in a[i] from last, and if after adding value is greater than 10\n \n { carry+=k%10;\n k/=10;}\n \n if(i>=0)\n { carry+=num[i--];}\n \n ans.push_back(carry%10);// than we using carry%10 and left carry is stored by carry/=10 , and used further \n carry/=10;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\nhoped you understood man , happy coding (if you are an indian than definetly you will upvote this)\n```\n | 4 | 0 | ['C', 'C++'] | 0 |
add-to-array-form-of-integer | JAVA very easy Solution less than 90.59% memory O(n) time | java-very-easy-solution-less-than-9059-m-se50 | Please Upvote if you find this helpful\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayL | nesarptr | NORMAL | 2022-04-03T07:28:45.056183+00:00 | 2022-04-03T07:28:45.056221+00:00 | 255 | false | ***Please Upvote if you find this helpful***\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayList<>();\n int sum = 0;\n for (int i = num.length; i > 0; i--) {\n if (k > 0) {\n sum = sum + (k % 10) + num[i-1];\n list.add(0, sum % 10);\n k /= 10;\n }\n else {\n sum += num[i-1];\n list.add(0, sum % 10);\n }\n sum /= 10;\n }\n while (sum > 0 || k > 0) {\n sum += k % 10;\n list.add(0, sum % 10);\n sum /= 10; k /= 10;\n }\n return list;\n }\n}\n```\n***Please Upvote if you find this helpful***\n\n | 4 | 0 | [] | 2 |
add-to-array-form-of-integer | Java | O(n) Time | O(n) Space | java-on-time-on-space-by-hawtsauce-iwnl-b1bu | \nclass Solution {\n // O(n) Time | O(n) Space\n public List<Integer> addToArrayForm(int[] num, int k) {\n int n = num.length;\n ArrayList<I | hawtsauce-iwnl | NORMAL | 2021-08-26T06:42:51.421099+00:00 | 2021-08-26T06:51:23.251461+00:00 | 421 | false | ```\nclass Solution {\n // O(n) Time | O(n) Space\n public List<Integer> addToArrayForm(int[] num, int k) {\n int n = num.length;\n ArrayList<Integer> list = new ArrayList<>();\n for(int i = n - 1; i >= 0; i--) { \n int sum = num[i] + k;\n list.add(sum % 10); // Inserting at the end of arraylist takes O(1) time.\n k = sum / 10;\n }\n while(k > 0) {\n list.add(k % 10); \n k = k / 10;\n }\n Collections.reverse(list); // Reversing will take O(n) time.\n return list;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | Simple Java Solution | Faster than 99.61% | 2ms | simple-java-solution-faster-than-9961-2m-gmsi | \nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n \n LinkedList<Integer> result = new LinkedList();\n \n | vibhuteevala | NORMAL | 2021-05-27T20:52:15.778102+00:00 | 2021-05-27T20:52:58.422145+00:00 | 475 | false | ```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n \n LinkedList<Integer> result = new LinkedList();\n \n int sum = 0;\n int carry = 0;\n int i = num.length - 1;\n int data = 0;\n \n while(i >= 0 && k > 0){\n sum = num[i] + (k % 10) + carry;\n carry = sum / 10;\n result.addFirst(sum % 10);\n i--;\n k = k/10;\n }\n while(k > 0){\n sum = (k % 10) + carry;\n carry = sum / 10;\n result.addFirst(sum % 10);\n k = k/10;\n }\n while(i >= 0){\n sum = num[i] + carry;\n carry = sum / 10;\n result.addFirst(sum % 10);\n i--;\n }\n if(carry > 0)\n result.addFirst(carry);\n \n return result;\n \n }\n}\n``` | 4 | 1 | ['Java'] | 0 |
add-to-array-form-of-integer | Python easy solution | python-easy-solution-by-oleksam-r3bc | \nclass Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n # prepare original number\n str_numbers_list = [str(number) | oleksam | NORMAL | 2020-04-01T18:39:39.205759+00:00 | 2020-04-01T18:40:09.094133+00:00 | 311 | false | ```\nclass Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n # prepare original number\n str_numbers_list = [str(number) for number in A]\n number = int("".join(str_numbers_list))\n\n # prepare and return the answer\n number += K\n res = [int(x) for x in str(number)] \n return res\n``` | 4 | 0 | [] | 1 |
add-to-array-form-of-integer | Simple and Intutive Solution | simple-and-intutive-solution-by-chauhans-gvv1 | Intuition \n\nThe problem involves adding a large integer represented as an array (num) to another integer (k). The idea is to simulate the addition process as | chauhansujal | NORMAL | 2024-08-09T11:13:22.030799+00:00 | 2024-08-10T19:10:52.119253+00:00 | 306 | false | # Intuition \n\nThe problem involves adding a large integer represented as an array (`num`) to another integer (`k`). The idea is to simulate the addition process as we do manually, digit by digit from right to left.\n\nConsider this example:\n- `num = [1, 2, 3]` (which represents 123)\n- `k = 789`\n\n### The approach:\n1. Start from the last digit of `num` (i.e., the least significant digit) and add it to the last digit of `k`.\n2. If there\'s a carry, it will be added to the next digit in the next iteration.\n3. Continue this process, moving from right to left across `num`, while simultaneously reducing `k` by dividing it by 10.\n4. The loop continues until there are no digits left in both `num` and `k`.\n\nThe result is stored in reverse order as we append digits to the front of the list (or reverse the list later).\n\n# Complexity\n\n- **Time Complexity:** \\( O(n + \\log_{10} k) \\)\n - We traverse through the array `num` which has `n` elements.\n - Additionally, in each iteration, we reduce `k` by dividing it by 10, which takes \\( \\log_{10} k \\) steps.\n - Since `k` could have more digits than `num`, the time complexity can be considered as \\( O(\\max(n, \\log_{10} k)) \\).\n\n- **Space Complexity:** \\( O(n + \\log_{10} k) \\)\n - The space is used to store the result. Although we\u2019re not using any additional auxiliary space apart from the result list, the size of this list could be as large as the number of digits in `num` or `k`.\n\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n int n = num.length;\n ArrayList<Integer> list = new ArrayList<>();\n int i = n - 1;\n while (i >= 0 || k > 0) {\n if (i >= 0) {\n k += num[i];\n }\n list.add(0, k % 10);\n k /= 10;\n i--;\n }\n return list;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
add-to-array-form-of-integer | Easy & Simple Solution In Java || Sum and Carry Technique 💥👍 | easy-simple-solution-in-java-sum-and-car-styu | Intuition\nsum of last numbers and carry and add to the ans and reverse it.\n\n# Approach\n1. make a list name as a ans.\n2. loop will start begin grom num.leng | Rutvik_Jasani | NORMAL | 2024-02-25T06:42:22.759548+00:00 | 2024-02-25T06:42:22.759581+00:00 | 86 | false | # Intuition\nsum of last numbers and carry and add to the ans and reverse it.\n\n# Approach\n1. make a list name as a ans.\n2. loop will start begin grom num.length-1 to end i>=0 or k!=0.\n3. make sum and carry the value.\n4. reverse the ans liast and returrn it.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n int sum,carry=0;\n ArrayList<Integer> ans = new ArrayList<>();\n for(int i=num.length-1;i>=0 || k!=0;i--){\n if(i>=0){\n sum = (k%10) + num[i] + carry;\n }else{\n sum = (k%10) + carry;\n }\n k=k/10;\n carry = sum/10;\n int result = sum%10;\n ans.add(result);\n }\n if(carry>0){\n ans.add(carry);\n }\n int i=0;\n int j= ans.size()-1;\n int temp;\n while(i<j){\n temp = ans.get(i);\n ans.set(i,ans.get(j));\n ans.set(j,temp);\n i++;\n j--;\n }\n return ans;\n }\n}\n``` | 3 | 0 | ['Array', 'Math', 'Java'] | 0 |
add-to-array-form-of-integer | JavaScript | Beats 100% | Simple Solution | Explained | javascript-beats-100-simple-solution-exp-94qv | \n# Approach\n Describe your approach to solving the problem. \nThe problem appears to be about adding a number represented by an array (num) to another number | eduardko2001 | NORMAL | 2023-12-24T21:04:05.115006+00:00 | 2023-12-24T21:04:05.115025+00:00 | 275 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem appears to be about adding a number represented by an array (num) to another number k. The array represents a non-negative integer, and the goal is to return the result as an array.\n\nThe approach involves simulating the addition process, starting from the least significant digit (rightmost) and moving towards the most significant digit (leftmost). We iterate through the array num and add the corresponding digit from k. If there\'s a carry, it is propagated to the next iteration.\n\n# Complexity\n- Time complexity: $$O(max(N, log(k)))$$, where `N` is the length of the `num` array and `k` is the value of the input parameter `k`. This is because, in the worst case, the algorithm iterates through the entire `num` array, and the number of digits in `k` (log(k)).\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```\n/**\n * @param {number[]} num\n * @param {number} k\n * @return {number[]}\n */\nvar addToArrayForm = function(num = [0], k = 1000) {\n for (let i = num.length - 1; i >= 0; i--) {\n let sum = num[i] + k;\n num[i] = sum % 10;\n k = Math.floor(sum / 10);\n }\n\n // Handle remaining carry\n while (k > 0) {\n num.unshift(k % 10);\n k = Math.floor(k / 10);\n }\n\n return num;\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
add-to-array-form-of-integer | Java straight froward easy solution ||easy Approach | java-straight-froward-easy-solution-easy-qeia | Intuition\nEasy Java Solution \n\n# Approach\njust like orthodox addition method ie..\n 1 2 \n+ 5\n____\n 1 7\n\nhere we are adding numbers from end of array a | harshverma2702 | NORMAL | 2023-02-16T16:52:34.939082+00:00 | 2023-02-16T16:52:34.939126+00:00 | 131 | false | # Intuition\nEasy Java Solution \n\n# Approach\njust like orthodox addition method ie..\n 1 2 \n+ 5\n____\n 1 7\n\nhere we are adding numbers from end of array a keeping an carry for further addition purpose \n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n) , for answer set List for solution we do not require any space ie. O(1)\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> list = new ArrayList<>();\n int carry =0;\n for(int i =num.length-1;i>=0;i--){\n int n = k%10;\n k = k/10;\n int total = n+num[i]+carry;\n if(total>9){\n carry = 1;\n total = total%10;\n }\n else if(total<=9){\n carry=0;\n }\n list.add(0,total);\n }\n if(k>0){\n while(k>0){\n int n = k%10;\n k = k/10;\n int total = n+carry;\n if(total>9){\n carry = 1;\n total = total%10;\n }\n else if(total<=9){\n carry=0;\n }\n list.add(0,total);\n }\n }\n if(carry==1){\n list.add(0,1);\n }\n return list;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | 1 line Python Solution || Beats 98.4% in memory | 1-line-python-solution-beats-984-in-memo-8mzb | \n\n# Approach\n Describe your approach to solving the problem. \n1. turn each element on nums into a string \n\nmap(str,num)\n\n2. concate the elements of the | MohMantawy | NORMAL | 2023-02-15T16:29:33.376285+00:00 | 2023-02-15T16:29:33.376316+00:00 | 432 | false | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. turn each element on nums into a string \n```\nmap(str,num)\n```\n2. concate the elements of the array together\n```\n\'\'.join(map(str,num))\n```\n3. type cast into int and add k\n```\nint(\'\'.join(map(str,num))) + k\n```\n4. type cast into string\n```\nstr(int(\'\'.join(map(str,num)))+k)\n```\n5. create a list after type casting each char of the string into int\n```\nlist(map(int,str(int(\'\'.join(map(str,num)))+k)))\n```\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ ; where n = len(num)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\ndon\'t know how to actually compute it, let me know in the comments.\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(map(int,str(int(\'\'.join(map(str,num)))+k)))\n \n``` | 3 | 0 | ['Python3'] | 1 |
add-to-array-form-of-integer | || 🐍 Python3 || One-Line || Easiest ✔ Solution 🔥 || Beats 66% (Runtime) & 65% (Memory) || | python3-one-line-easiest-solution-beats-n2v0x | Intuition\nEasy problem with one line solution where num list is joined to form an int and then added to k and again converted to list.\n\n# Approach\nAlthough | Samurai_Omu | NORMAL | 2023-02-15T16:27:23.157897+00:00 | 2023-02-15T16:27:23.157942+00:00 | 608 | false | # Intuition\nEasy problem with one line solution where `num` list is joined to form an int and then added to `k` and again converted to list.\n\n# Approach\nAlthough its a one-line solution, there are multiple steps involved.\n1. Iterating through the `nums` list while converting each element to `str` and then joining them. Now this joined string will be converted to `int`.\n2. The `int` obtained in Step-1 will be added to `k` and then the `sum` is again converted to string.\n3. Now, iterate over the `sum` string into `list` while converting each element to `int`.\n\n# Complexity\n- Time complexity : $$O(log(len(num)^2 + k))$$\n- Space complexity : $$O(1)$$\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return [int(i) for i in str(k+ int(\'\'.join(str(n) for n in num)))]\n```\n---\n\n### Happy Coding \uD83D\uDC68\u200D\uD83D\uDCBB\n\n---\n\n### If this solution helped you then do consider Upvoting \u2B06.\n#### Lets connect on LinkedIn : [Om Anand](https://www.linkedin.com/in/om-anand-38341a1ba/) \uD83D\uDD90\uD83D\uDE00\n---\n\n### Comment your views/corrections \uD83D\uDE0A\n | 3 | 0 | ['Array', 'Math', 'Python3'] | 0 |
add-to-array-form-of-integer | Easy 1 liner in C# with LINQ | easy-1-liner-in-c-with-linq-by-davidlind-hbwc | Here is an easy to understand 1 liner\n\n# Approach\n1. Convert the num array to a string\n2. Parse as a number\n3. Add k\n4. Convert value to string\n5. Conver | davidlindon | NORMAL | 2023-02-15T15:40:47.790674+00:00 | 2023-02-15T15:40:47.790717+00:00 | 474 | false | Here is an easy to understand 1 liner\n\n# Approach\n1. Convert the num array to a string\n2. Parse as a number\n3. Add k\n4. Convert value to string\n5. Convert each element to an int\n6. Build list to return\n\n# Code\n```\nusing System.Numerics;\npublic class Solution {\n public IList<int> AddToArrayForm(int[] num, int k) {\n return (BigInteger.Parse(string.Join("", num.Select(x => x))) + k).ToString().Select(x => int.Parse(x.ToString())).ToList();\n }\n}\n``` | 3 | 0 | ['C#'] | 1 |
add-to-array-form-of-integer | easy solution in c++ | easy-solution-in-c-by-shubhi_115-ihji | Intuition\n Describe your first thoughts on how to solve this problem. \nMove from write to left, k is the carry, add num[i]+k, num[i]=lastdigit\nand k = alldig | shubhi_115 | NORMAL | 2023-02-15T14:38:31.395674+00:00 | 2023-02-15T14:38:31.395723+00:00 | 436 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMove from write to left, k is the carry, add num[i]+k, num[i]=lastdigit\nand k = alldigits except last digit .... do so on.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n for(int i=num.size()-1;i>=0;i--){\n num[i] += k;\n k = num[i]/10;\n num[i] %= 10;\n }\n while(k > 0){\n num.insert(num.begin(), k%10);\n k /= 10;\n }\n return num;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
add-to-array-form-of-integer | 0ms/simple java solution/easy to understand/beginner friendly | 0mssimple-java-solutioneasy-to-understan-bdi0 | 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 | antovincent | NORMAL | 2023-02-15T14:22:35.224052+00:00 | 2023-02-15T14:22:35.224096+00:00 | 38 | 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 List<Integer> addToArrayForm(int[] num, int k) {\n List<Integer> r = new ArrayList<>();\n int l=num.length-1;\n int c=0;\n while(l>=0||k>0){\n int sum=c;\n if(l>=0){\n sum+=num[l];\n l--;\n }\n if(k>=0){\n sum+=(k%10);\n k/=10;\n }\n r.add(sum%10);\n c=sum/10;\n }\n if(c>0){\n r.add(c);\n }\n Collections.reverse(r);\n return r;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | ✅C++ | ✅Easy to Understand | c-easy-to-understand-by-yash2arma-998l | Code\n\nclass Solution \n{\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) \n {\n int carry=0, sum, i=num.size()-1;\n while(k | Yash2arma | NORMAL | 2023-02-15T08:28:18.499678+00:00 | 2023-02-15T08:28:18.499806+00:00 | 707 | false | # Code\n```\nclass Solution \n{\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) \n {\n int carry=0, sum, i=num.size()-1;\n while(k || carry)\n {\n sum = carry + k%10;\n k /= 10;\n\n if(i>=0)\n {\n sum += num[i];\n num[i] = sum%10;\n i--;\n }\n else\n {\n num.insert(num.begin(), sum%10);\n }\n carry = sum/10;\n }\n return num;\n \n }\n};\n``` | 3 | 0 | ['Array', 'Math', 'C++'] | 0 |
add-to-array-form-of-integer | Super Easy JAVA Sol. | super-easy-java-sol-by-harsh_tiwari-qrwu | 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 | harsh_tiwari_ | NORMAL | 2023-02-15T08:14:26.160706+00:00 | 2023-02-15T08:14:26.160752+00:00 | 345 | 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 List<Integer> addToArrayForm(int[] num, int k) {\n LinkedList<Integer> ans = new LinkedList<>();\n int len = num.length-1;\n while(len >= 0 || k != 0){\n if(len >= 0){\n k += num[len];\n len--;\n }\n ans.addFirst(k % 10);\n k = k/10;\n } \n return ans;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | [Python]Simple solution for noobs (for people new to coding) | pythonsimple-solution-for-noobs-for-peop-thfk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. Using brute force to look | bot16111011 | NORMAL | 2023-02-15T07:34:55.681656+00:00 | 2023-02-15T07:34:55.681704+00:00 | 194 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Using brute force to look.\nfirst for loop is used to convert the list to number.\nthen we store the acquired number in **s**\nAdd the k in s then loop the s and enter the digits in empty list named **lst** \nBut this new list will have result in reverse order so we will return it by reversing it as **lst[::-1]**\n\nNote: for better understanding take a list containing not more than 2 elements and run through the code.Also you can use jupyter or use print statement after steps how the code is progressing.\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def addToArrayForm(self, num, k):\n """\n :type num: List[int]\n :type k: int\n :rtype: List[int]\n """\n s=0\n for i in num:\n s=s*10+i\n s=s+k\n lst=[]\n while(s!=0):\n lst.append(s%10)\n s=s//10\n return lst[::-1]\n\n``` | 3 | 0 | ['Python'] | 0 |
add-to-array-form-of-integer | JAVA EASY to UNDERSTAND Solution | java-easy-to-understand-solution-by-hars-f3oy | \n# Approach\nJUST SIMPLE ADDITION.\n\nTIP : use LinkedList instead of ArrayList.\n\n# Complexity\n- Time complexity : O(n)\n\n- Space complexity: O(1)\n\n# Cod | harshgupta4949 | NORMAL | 2023-02-15T06:37:29.740927+00:00 | 2023-02-15T06:37:29.740970+00:00 | 460 | false | \n# Approach\nJUST SIMPLE ADDITION.\n\nTIP : use LinkedList instead of ArrayList.\n\n# Complexity\n- Time complexity : O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n int n=num.length;\n List<Integer> l=new LinkedList<>();\n for(int i=0;i<n||k!=0;i++){\n if(i<n) k+=num[n-i-1];\n l.add(0,k%10);\n k=k/10;\n }\n return l;\n }\n}\n``` | 3 | 0 | ['Linked List', 'Math', 'Java'] | 2 |
add-to-array-form-of-integer | Optimized Solution in C++ | optimized-solution-in-c-by-devanshu_ragh-90ga | Intuition\nWe can optimize the solution to avoid the integer conversion and make it more efficient. Instead of computing the sum of the input integer and k digi | Devanshu_Raghav | NORMAL | 2023-02-15T06:24:08.828180+00:00 | 2023-02-15T06:24:08.828218+00:00 | 406 | false | # Intuition\nWe can optimize the solution to avoid the integer conversion and make it more efficient. Instead of computing the sum of the input integer and k digit by digit, we can directly add k to the least significant digit of the input integer and carry over the result to the higher digits. This way, we can build the array-form of the sum digit by digit, without having to convert the input integer to an integer.\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int> res;\n int carry = k;\n \n for (int i = num.size() - 1; i >= 0 || carry > 0; i--) {\n if (i >= 0) {\n carry += num[i];\n }\n res.push_back(carry % 10);\n carry /= 10;\n }\n \n reverse(res.begin(), res.end());\n return res;\n}\n};\n``` | 3 | 0 | ['Array', 'C++'] | 1 |
add-to-array-form-of-integer | One Line, JS | one-line-js-by-mrsalvation-sbz2 | \n\nconst addToArrayForm = (nums, k) => (BigInt(nums.join(\'\')) + BigInt(k)).toString().split(\'\')\n\n | mrsalvation | NORMAL | 2023-02-15T06:11:38.664890+00:00 | 2023-02-15T06:11:38.664935+00:00 | 859 | false | ```\n\nconst addToArrayForm = (nums, k) => (BigInt(nums.join(\'\')) + BigInt(k)).toString().split(\'\')\n\n``` | 3 | 0 | ['JavaScript'] | 1 |
add-to-array-form-of-integer | Easy approach used in multiple problems | easy-approach-used-in-multiple-problems-htikn | Intuition\nSimilar problems are:\n-> Add Two Numbers\n-> Plus One\n-> Add Binary\n-> Add Strings\n\n# Approach\nfirst convert given k into vector.\nNow place tw | harsh_patell21 | NORMAL | 2023-02-15T05:26:30.811856+00:00 | 2023-02-15T05:26:30.811897+00:00 | 33 | false | # Intuition\nSimilar problems are:\n-> Add Two Numbers\n-> Plus One\n-> Add Binary\n-> Add Strings\n\n# Approach\nfirst convert given k into vector.\nNow place two pointer.\nOne at the last of first vector.\nSecond pointer at the last of second vector.\nThere is also a variable carry which is used for carry as well as sum of two number at i and j index.\n\n\n# Complexity\n- Time complexity:\n$$O(max(len(num1),len(num2)))$$\n\n- Space complexity:\n$$O(max(len(num1),len(num2)))$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num1, int k) {\n vector<int>num2;\n// Converting k into vector\n while(k){ \n num2.push_back(k%10);\n k=k/10;\n }\n reverse(num2.begin(),num2.end());\n// Reverse the vector\n vector<int>vect;\n// First pointer at the end of num1\n int i=num1.size()-1;\n// Second pointer at the end of num2\n int j=num2.size()-1;\n int carry=0;\n while(i>=0 || j>=0 || carry){\n// condition is running untill array has element.\n if(i>=0){\n carry+=num1[i];\n i--;\n }\n// condition is running untill array has element.\n if(j>=0){\n carry+=num2[j];\n j--;\n }\n vect.push_back(carry%10);\n carry=carry/10;\n }\n// reverse the \n reverse(vect.begin(),vect.end());\n return vect;\n }\n};\n``` | 3 | 1 | ['C++'] | 0 |
add-to-array-form-of-integer | || Understandable C++ Solution || | understandable-c-solution-by-shantanubho-6si1 | 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 | shantanubhojak | NORMAL | 2023-02-15T04:58:03.836512+00:00 | 2023-02-15T04:58:03.836559+00:00 | 597 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int carry=0;\n int n=num.size();\n for(int i=n-1;i>=0 ;i--)\n {\n int temp=carry+(k%10)+num[i]; // performing addition \n carry=temp/10; // calculating carry\n num[i]=temp%10;\n k=k/10;\n }\n while(k) //if k is greater than num\'s size \n {\n int temp=(k%10)+carry;\n num.insert(num.begin(),temp%10);\n carry=temp/10;\n k/=10;\n }\n if(carry >0) num.insert(num.begin(),carry); // if at last carry is left we need to insert it\n // at the beginnnig \n return num;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
add-to-array-form-of-integer | Simple beginner solution || Addition-carry concept ||✔ | simple-beginner-solution-addition-carry-xfrls | \n\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int n=num.size();\n vector<int> ans;\n int carry | Ayuk_05 | NORMAL | 2023-02-15T04:55:22.621196+00:00 | 2023-02-15T04:55:22.621236+00:00 | 192 | false | \n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int n=num.size();\n vector<int> ans;\n int carry=0;\n for(int i=n-1;i>=0;--i){\n int res=num[i]+k%10+ carry;\n ans.push_back(res%10);\n carry=res/10;\n k=k/10;\n \n }\n \n while(k){\n int res=carry+k%10;\n ans.push_back(res%10);\n carry=res/10;\n k=k/10;\n }\n if(carry){\n ans.push_back(carry);\n }\n \n reverse(ans.begin(),ans.end());\n \n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'Math', 'C++'] | 0 |
add-to-array-form-of-integer | Rust easy solution | rust-easy-solution-by-williamcs-3ww6 | \n\nimpl Solution {\n pub fn add_to_array_form(num: Vec<i32>, k: i32) -> Vec<i32> {\n let mut k = k;\n let mut res = vec![];\n let mut j | williamcs | NORMAL | 2023-02-15T03:25:34.864156+00:00 | 2023-02-15T03:25:34.864201+00:00 | 1,444 | false | \n```\nimpl Solution {\n pub fn add_to_array_form(num: Vec<i32>, k: i32) -> Vec<i32> {\n let mut k = k;\n let mut res = vec![];\n let mut j = num.len();\n let mut carry = 0;\n\n while j > 0 || k > 0 || carry > 0 {\n if j > 0 {\n carry += num[j - 1];\n j -= 1;\n }\n\n carry += k % 10;\n k /= 10;\n\n res.push(carry % 10);\n carry /= 10;\n }\n\n res.reverse();\n res\n }\n}\n``` | 3 | 0 | ['Rust'] | 0 |
add-to-array-form-of-integer | Java | LinkedList | 10 lines | Beats > 97% | java-linkedlist-10-lines-beats-97-by-jud-nyv4 | 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 | judgementdey | NORMAL | 2023-02-15T00:59:22.310976+00:00 | 2023-02-15T01:01:59.217576+00:00 | 26 | 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(max(N,logK))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(max(N,logK))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n var ans = new LinkedList<Integer>();\n var carry = 0;\n\n for (var i = num.length - 1; i >= 0 || k > 0 ; i--, k /= 10) {\n var a = i >= 0 ? num[i] : 0;\n var b = k > 0 ? k % 10 : 0;\n var c = a + b + carry;\n\n ans.addFirst(c % 10);\n carry = c / 10;\n }\n if (carry > 0) ans.addFirst(carry);\n return ans;\n }\n}\n``` | 3 | 0 | ['Doubly-Linked List', 'Java'] | 0 |
add-to-array-form-of-integer | Python3 🚀🚀|| Simple solution and explained || O(n)👀. | python3-simple-solution-and-explained-on-eqtz | Approach\n Describe your approach to solving the problem. \n- First I converted list into string format in order to make it as number.\n- Then I added the num a | Kalyan_2003 | NORMAL | 2023-02-04T13:22:03.072437+00:00 | 2023-02-04T13:22:03.072479+00:00 | 693 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- First I converted list into string format in order to make it as number.\n- Then I added the num and K and then converted the result into string again to convert from string format to list and assigned to str_list.\n- Later converted the str_list into int by using map function and assigned it to final_str_list and returned it.\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n s = ""\n for i in num:\n s+=str(i)\n str_list = " ".join(str(int(s)+k)).split()\n final_list = list(map(int,str_list))\n return final_list\n```\n# Please upvote if you find the solution helpful. | 3 | 0 | ['Array', 'Math', 'Python3'] | 1 |
add-to-array-form-of-integer | Python3 | One line solution | python3-one-line-solution-by-manfrommoon-kze8 | \nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(str(int("".join([str(x) for x in num])) + k))\n | manfrommoon | NORMAL | 2022-05-14T11:52:34.613474+00:00 | 2022-05-14T12:02:39.029403+00:00 | 519 | false | ```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(str(int("".join([str(x) for x in num])) + k))\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
add-to-array-form-of-integer | Python3 | hold my beer | python3-hold-my-beer-by-anilchouhan181-j9hd | One line solution\n\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return [int(i) for i in str(int(\'\'.join([str | Anilchouhan181 | NORMAL | 2022-02-23T19:40:48.118670+00:00 | 2022-02-23T19:40:48.118718+00:00 | 378 | false | **One line solution**\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return [int(i) for i in str(int(\'\'.join([str(i) for i in num]))+k)]\n``` | 3 | 1 | ['Python', 'Python3'] | 0 |
add-to-array-form-of-integer | java easy code | java-easy-code-by-rakesh_sharma_4-ybsk | \nclass Solution {\n public List<Integer> addToArrayForm(int[] nums, int k) {\n List<Integer> list=new ArrayList<>();\n int i=nums.length-1;\n | Rakesh_Sharma_4 | NORMAL | 2022-01-21T01:08:15.532339+00:00 | 2022-01-21T01:08:15.532367+00:00 | 327 | false | ```\nclass Solution {\n public List<Integer> addToArrayForm(int[] nums, int k) {\n List<Integer> list=new ArrayList<>();\n int i=nums.length-1;\n while(i>=0 || k>0)\n {\n if(i>=0)\n k=k+nums[i];\n list.add(k%10);\n k/=10;\n i--;\n }\n Collections.reverse(list);\n return list;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | java solution with complete explanation | java-solution-with-complete-explanation-mf09b | \n//refer screenshot for explanation\n\n\nclass Sol | chetandaulani1998 | NORMAL | 2021-12-05T02:06:42.302480+00:00 | 2021-12-05T02:12:26.844340+00:00 | 407 | false | ```\n//refer screenshot for explanation\n\n\nclass Solution {\n public List<Integer> addToArrayForm(int[] num, int k) {\n ArrayList<Integer> list = new ArrayList<>();\n \n for(int i=num.length-1; i>=0 || k>0; i--){\n \n if(i>=0){\n list.add((num[i]+k)%10);\n k=(num[i]+k)/10;\n }\n else{\n list.add(k%10);\n k/=10;\n }\n }\n \n Collections.reverse(list);\n return list;\n }\n}\n```\n | 3 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | Python 3 | very easy to understand | one-liner | python-3-very-easy-to-understand-one-lin-4f84 | \nreturn list(str(K + int("".join(map(str, A)))))\n | saishivau726 | NORMAL | 2021-01-15T06:58:50.437269+00:00 | 2021-01-15T06:58:50.437311+00:00 | 126 | false | ```\nreturn list(str(K + int("".join(map(str, A)))))\n``` | 3 | 1 | [] | 1 |
add-to-array-form-of-integer | C# O(n) solution | c-on-solution-by-newbiecoder1-c8v4 | Implementation\n Time complexity: O(N) where N is the length of A.\n Traversing the input array takes O(N). List.Add() is a O(1) operation. List.Reverse() is a | newbiecoder1 | NORMAL | 2020-11-11T08:15:59.954016+00:00 | 2020-11-11T08:15:59.954052+00:00 | 172 | false | # Implementation\n* Time complexity: O(N) where N is the length of A.\n Traversing the input array takes O(N). List.Add() is a O(1) operation. List.Reverse() is a O(N) operation. \n \n* Space complexity: O(N)\n```\npublic class Solution {\n public IList<int> AddToArrayForm(int[] A, int K) {\n \n int carry = K, i = A.Length - 1;\n \n List<int> res = new List<int>();\n while(i >= 0 || carry > 0)\n {\n int val = i >= 0? A[i] : 0;\n int sum = val + carry;\n carry = sum / 10;\n res.Add(sum % 10);\n i--;\n }\n \n res.Reverse();\n return res;\n }\n}\n```\n\n# Some thoughts\nUsing List.Insert() to build result from LSD (least significant digit)to MSD (most significant digit) will save a Reverse. However, List.Insert() is a O(N) operation, so below implemetation has O(N^2) time complexity.\n```\npublic class Solution {\n public IList<int> AddToArrayForm(int[] A, int K) {\n \n char[] B = K.ToString().ToArray();\n \n int carry = 0, i1 = A.Length - 1, i2 = B.Length - 1;\n List<int> res = new List<int>();\n while(i1 >= 0 || i2 >= 0 || carry > 0)\n {\n int val1 = i1 >= 0? A[i1] : 0;\n int val2 = i2 >= 0? B[i2] - \'0\' : 0;\n int sum = val1 + val2 + carry;\n carry = sum / 10;\n res.Insert(0, sum % 10);\n i1--;\n i2--;\n }\n \n return res;\n }\n}\n```\n\nWe can also use LinkedList to build the result. Unlike List<T> whose underlying data structure is Array, LinkedList<T> underlying data structure is a double linked list. LinkedList.AddFirst() is a O(1) operation and we can use it to build the result from LSD to MSD. Below solution will have O(N) time complexity.\n```\npublic class Solution {\n public IList<int> AddToArrayForm(int[] A, int K) {\n \n char[] B = K.ToString().ToArray();\n \n int carry = 0, i1 = A.Length - 1, i2 = B.Length - 1;\n LinkedList<int> res = new LinkedList<int>();\n while(i1 >= 0 || i2 >= 0 || carry > 0)\n {\n int val1 = i1 >= 0? A[i1] : 0;\n int val2 = i2 >= 0? B[i2] - \'0\' : 0;\n int sum = val1 + val2 + carry;\n carry = sum / 10;\n res.AddFirst(sum % 10);\n i1--;\n i2--;\n }\n \n return new List<int>(res);\n }\n}\n``` | 3 | 0 | [] | 1 |
add-to-array-form-of-integer | Python two solutions: type conversion and normal mod | python-two-solutions-type-conversion-and-sl9t | \nclass Solution:\n def addToArrayForm(self, A: \'List[int]\', K: \'int\') -> \'List[int]\':\n """\n Method 1, convert A to an integer first, d | bigtony | NORMAL | 2019-02-12T18:18:46.169452+00:00 | 2019-02-12T18:18:46.169526+00:00 | 609 | false | ```\nclass Solution:\n def addToArrayForm(self, A: \'List[int]\', K: \'int\') -> \'List[int]\':\n """\n Method 1, convert A to an integer first, do the addition, finally convert to list\n """\n def list2int(l):\n s = list(map(str, l))\n s = \'\'.join(s)\n return int(s)\n \n def int2list(i):\n s = str(i)\n return list(map(int, s))\n \n return int2list(list2int(A) + K)\n \n """\n Method 2, Schoolbook Addition\n """\n for i in range(len(A) - 1, -1, -1):\n # Option 1: vanilla way to deal with remainder and quotient\n # K, A[i] =(A[i] + K) // 10, (A[i] + K) % 10\n # Option 2: use divmod()\n K, A[i] = divmod(A[i] + K, 10)\n \n # If K still has value, unshift it from head\n return list(map(int, str(K))) + A if K else A\n \n``` | 3 | 1 | [] | 1 |
add-to-array-form-of-integer | C | c-by-pavithrav25-nw27 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | pavithrav25 | NORMAL | 2024-12-28T04:21:57.781296+00:00 | 2024-12-28T04:21:57.781296+00:00 | 97 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* addToArrayForm(int* num, int numSize, int k, int* returnSize) {
int* arr = malloc((numSize + 10) * sizeof(int));
int i = numSize - 1, carry = k, j = 0;
while (i >= 0 || carry > 0) {
if (i >= 0) carry += num[i--];
arr[j++] = carry % 10;
carry /= 10;
}
for (int l = 0, r = j - 1; l < r; l++, r--) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
*returnSize = j;
return arr;
}
``` | 2 | 0 | ['C'] | 0 |
add-to-array-form-of-integer | easy solution | easy-solution-by-leet1101-8hcb | Intuition\nThe problem can be reduced to a simple addition of two numbers: one represented as an array (num) and the other as an integer (k). We need to simulat | leet1101 | NORMAL | 2024-10-01T11:43:34.692642+00:00 | 2024-10-01T11:43:34.692669+00:00 | 196 | false | # Intuition\nThe problem can be reduced to a simple addition of two numbers: one represented as an array (`num`) and the other as an integer (`k`). We need to simulate this addition starting from the least significant digits (rightmost elements) and handling carry over.\n\n# Approach\n1. Start from the rightmost digit of the array (`num`) and the least significant digit of `k`.\n2. Add the corresponding digits from `num` and `k`, along with any carry.\n3. If `num` has more digits than `k`, continue processing `num`.\n4. If `k` has more digits than `num`, insert digits at the beginning of `num`.\n5. Handle carry as needed throughout the process.\n6. Return the modified `num` array.\n\n# Complexity\n- **Time complexity**: $$O(\\max(n, \\log{k}))$$ \n Where `n` is the size of `num`, and `log{k}` is the number of digits in `k`.\n \n- **Space complexity**: $$O(1)$$ \n In-place modifications to `num` (except for inserting digits, which happens at the front but is not considered additional space).\n\n# Code\n```cpp\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n int carry = 0;\n int i = num.size() - 1;\n \n while (k || i >= 0 || carry) {\n int digit = k % 10;\n\n if (i >= 0) {\n num[i] += digit + carry;\n carry = num[i] / 10;\n num[i] %= 10;\n i--;\n } else {\n int sum = digit + carry;\n carry = sum / 10;\n num.insert(num.begin(), sum % 10);\n }\n\n k /= 10;\n }\n return num;\n }\n};\n``` | 2 | 0 | ['Array', 'Math', 'C++'] | 1 |
add-to-array-form-of-integer | 2 approaches - Using Python Built-In Functions & Maths - Explained with comments | 2-approaches-using-python-built-in-funct-iaaj | Using Built-in functions\n\nimport sys\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # Set the maximum number of | TrGanesh | NORMAL | 2024-08-17T17:56:01.608444+00:00 | 2024-08-17T17:56:01.608471+00:00 | 152 | false | #### Using Built-in functions\n```\nimport sys\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # Set the maximum number of digits allowed in an integer to handle large numbers\n # sys.set_int_max_str_digits(100000) is used to prevent overflow errors in large integer operations\n sys.set_int_max_str_digits(100000) # ******** Important ***************\n \n # Convert the list of digits in \'num\' to a string, then concatenate the string into a single integer.\n # Example: num = [1,2,3] -> \'123\' -> 123\n int_num = int(\'\'.join(map(str, num)))\n \n # Add the integer \'k\' to the integer representation of \'num\'\n ans_int = int_num + k\n \n # Convert the resulting integer back into a string, then split the string into a list of characters (digits)\n # Example: 456 -> \'456\' -> [\'4\', \'5\', \'6\']\n ans_str_list = list(str(ans_int))\n \n # Map each character (digit) back to an integer, converting the string digits to integers\n # Example: [\'4\', \'5\', \'6\'] -> [4, 5, 6]\n ans_int_list = list(map(int, ans_str_list))\n \n # Return the final result, which is the array-form of the sum of \'num\' and \'k\'\n return ans_int_list\n```\n---\n#### Using Maths\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # Initialize a pointer to the last digit of the num array\n i = len(num) - 1\n \n # Process the addition from the last digit of the array and k\n while k > 0:\n # If i is still within the bounds of the num array, add k to the current digit\n if i >= 0:\n # Add the last digit of k to the num[i] (adding carry to the num)\n num[i] += k\n # Calculate the carry by performing integer division by 10\n k = num[i] // 10\n # Update the current digit in num after removing the carry\n num[i] %= 10\n # Move to the previous digit in the num array\n i -= 1\n else:\n # If i is out of bounds, treat the remaining k as the carry to be inserted at the front\n num.insert(0, k % 10) # Insert the last digit of k to the front of the array\n k //= 10 # Remove the last digit from k (carry)\n \n return num # Return the resulting array-form after addition\n```\n**Please UpVote if you like the Code and Explanation** | 2 | 0 | ['Python3'] | 0 |
add-to-array-form-of-integer | Easy Java Solution || Math | easy-java-solution-math-by-ravikumar50-wum5 | 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 | ravikumar50 | NORMAL | 2024-03-20T14:22:33.516895+00:00 | 2024-03-20T14:22:33.516924+00:00 | 227 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\n\n public List<Integer> addToArrayForm(int[] arr, int k) {\n int n = arr.length;\n int c = 0;\n List<Integer> ans = new ArrayList<>();\n String x = String.valueOf(k);\n int idx = x.length()-1;\n for(int i=n-1; i>=0; i--){\n int a = arr[i];\n int b = (idx>=0) ? x.charAt(idx--)-48 : 0;\n int s = a+b+c;\n if(s>=10){\n c = s/10;\n ans.add(0,s%10);\n }else{\n ans.add(0,s);\n c=0;\n }\n }\n\n if(x.length()>arr.length){\n while(idx>=0){\n int b = x.charAt(idx--)-48;\n int s = b+c;\n if(s>=10){\n c = s/10;\n ans.add(0,s%10);\n }else{\n ans.add(0,s);\n c=0;\n }\n }\n }\n if(c!=0){\n ans.add(0,c);\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
add-to-array-form-of-integer | Perfectly Solved.. check once.. | perfectly-solved-check-once-by-anshdhard-torw | \n\n# Code\n```\nclass Solution {\npublic:\n vector addToArrayForm(vector& num, int k) {\n vectorans;\n vectorresult;\n reverse(num.begi | anshdhardwivedi23 | NORMAL | 2023-12-10T10:58:48.503594+00:00 | 2023-12-10T10:58:48.503624+00:00 | 349 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n vector<int>ans;\n vector<int>result;\n reverse(num.begin(),num.end());\n int i=0;\n int carry=0;\n while(i<num.size() || k || carry){\n // checking the condition in a single loop with style..\n // handle i carefully when it exceeded num.size..\n int first = (i < num.size()) ? num[i] : 0;\n // this is the sum..\n int sum= first+(k%10)+ carry;\n // to check carry..\n carry=sum/10;\n // pushing back..\n result.push_back(sum%10);\n // updating loop condition..\n k=k/10;\n i++; \n }\n reverse(result.begin(),result.end());\n return result; }\n}; | 2 | 0 | ['C++'] | 1 |
add-to-array-form-of-integer | Python 95% beats || 2 Approach || Simple Code | python-95-beats-2-approach-simple-code-b-kr75 | If you got help from this,... Plz Upvote .. it encourage me\n# Code\n# Approach 1 Array\n\nclass Solution(object):\n def addToArrayForm(self, A, K):\n | vvivekyadav | NORMAL | 2023-09-25T08:31:43.560812+00:00 | 2023-09-25T08:31:43.560836+00:00 | 342 | false | **If you got help from this,... Plz Upvote .. it encourage me**\n# Code\n# Approach 1 Array\n```\nclass Solution(object):\n def addToArrayForm(self, A, K):\n A[-1] += K\n for i in range(len(A) - 1, -1, -1):\n carry, A[i] = divmod(A[i], 10)\n if i: A[i-1] += carry\n if carry:\n A = list(map(int, str(carry))) + A\n return A\n\n```\n\n.\n\n# Approach 2 (By Convert list into number then add and then convert number into digit)\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # List -> Number\n n = 0\n for ele in num:\n n = (n*10) + ele\n \n n = n+k\n \n # Number -> List\n num = []\n while n > 0:\n num.insert(0, n % 10) \n n //= 10 \n return num\n``` | 2 | 0 | ['Array', 'Math', 'Python', 'Python3'] | 0 |
add-to-array-form-of-integer | Easy Approach ( C++ ) | easy-approach-c-by-yashikagupta14-8dn5 | 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 | YashikaGupta14 | NORMAL | 2023-08-26T03:53:17.065419+00:00 | 2023-08-26T03:53:17.065440+00:00 | 854 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic\n vector<int> addToArrayForm(vector<int>& nums, int k) {\n int n=nums.size();\n int i=n-1;\n int carry=0;\n vector<int> ans;\n while(i>=0)\n {\n int dig=k%10;\n k/=10;\n int sum=nums[i]+dig+carry;\n ans.push_back(sum%10);\n carry=sum/10;\n \n i--;\n }\n while(k)\n {\n int dig=k%10;\n k/=10;\n int sum=dig+carry;\n ans.push_back(sum%10);\n carry=sum/10;\n }\n if(carry>0)\n {\n ans.push_back(carry);\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
add-to-array-form-of-integer | C++|| 98.6% | c-986-by-shradhaydham24-hb45 | 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 | shradhaydham24 | NORMAL | 2023-08-02T13:02:23.822353+00:00 | 2023-08-02T13:02:23.822375+00:00 | 642 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int> &A, int K)\n {\n int i, size = A.size();\n\n for (i = size - 1; i >= 0 && K != 0; i--)\n {\n K = K + A[i];\n A[i] = K % 10;\n K = K / 10;\n }\n while (K != 0)\n {\n A.insert(A.begin(), K % 10);\n K = K / 10;\n }\n return A;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.