Adding Two Numbers :- The goal was to add two numbers represented as arrays and return the result as a new array. Approach Used : 1) Initialize two pointers Started from the last index of both arrays to simulate manual addition from right to left. 2) Use a carry variable Maintained a carry variable to handle cases where the sum of digits exceeds 9. 3) Handle unequal lengths safely If one array finishes earlier, treated its value as 0 using conditional logic. 4) Calculate sum and carry At each step: • sum = digit1 + digit2 + carry • store sum % 10 in result • update carry = sum / 10 5) Store result dynamically Used ArrayList to store digits since result size may vary. 6) Reverse the result Since digits were added from right to left, reversed the list to get the correct final order. This approach ensures efficient handling of carry and works for arrays of different lengths. Time Complexity: O(n) Space Complexity: O(n) #DSA #JAVA
Adding Two Numbers as Arrays in Java
More Relevant Posts
-
🚀 Day 33 / 100 | Partition List -Intuition: This problem is based on Linked List partitioning. We are given the head of a linked list and a value x. Goal is to rearrange the list such that all nodes with values less than x come before nodes with values greater than or equal to x. we must preserve the original relative order of nodes in each partition. "So instead of modifying values, we create two separate lists and then connect them". -Approach: O(n) Initialize two dummy nodes: l1 and l2. These will store nodes less than x and nodes greater than or equal to x respectively. Traverse the original linked list from head to null. If current node value < x, attach it to the small list. Otherwise, attach it to the greater list. Move the pointers accordingly. After traversal, connect the end of the small list to the start of the greater list. Make sure to set greater.next = null to avoid cycle. Return l1.next as the new head. -Complexity: Time Complexity: O(n) Space Complexity: O(1) #100DaysOfCode #Java #DSA #LeetCode #LinkedList
To view or add a comment, sign in
-
-
🚀 Day 23 / 100 | Add Two Numbers -Approach : O(n) - Traverse both linked lists simultaneously. - Maintain a carry variable to handle sums that are greater than or equal to 10. - Use a ans node to simplify the construction of the result list. - At each step, compute the sum as: sum = val1 + val2 + carry. - Update the carry as carry = sum / 10 and store sum % 10 in a new node. - Continue this process until both lists and the carry are exhausted. - Finally, return ans.next. #100DaysOfCode #LeetCode #Java #DSA #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
📌 Day 18 – GFG Problem of the Day 🧩 Trapping Rain Water Given an array representing heights of blocks, where width of each block is 1, we need to calculate how much rain water can be trapped between the blocks. 💡 Key Insight: Water trapped at any index depends on: 👉 Maximum height on the left 👉 Maximum height on the right Water at index i = min(leftMax[i], rightMax[i]) − height[i] ✨ Approach (Prefix & Suffix Arrays): • Build leftMax[] array (maximum till left) • Build rightMax[] array (maximum till right) • For each index, add min(leftMax[i], rightMax[i]) - arr[i] • Sum gives total trapped water ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) #GeeksforGeeks #ProblemOfTheDay #DSA #Java #Arrays #PrefixSuffix #TwoPointers #CodingJourney #PlacementPrep #LearningEveryday
To view or add a comment, sign in
-
-
Array Rotation using Reverse Algorithm (Java) I recently solved an interesting array problem where the goal was to rotate an array efficiently without using extra space. Instead of shifting elements multiple times, I implemented the Reverse Algorithm, which optimizes the solution to O(n) time complexity and O(1) space. 🔹 Approach Used: 1 Reverse first d elements 2 Reverse remaining elements 3 Reverse the entire array
To view or add a comment, sign in
-
-
link 🔗 : https://lnkd.in/gEWHSEyy problem 509 : Fibonacci numbers The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Constraints: 0 <= n <= 30 #DSA #LeetCode #problemOfTheDay #Java
To view or add a comment, sign in
-
-
🌳 Day 72/100: Diameter of Binary Tree - Height While Calculating Day 72. Find longest path between any two nodes. Track diameter while calculating height. Smart. ✅ 📌 Problem: Find diameter (longest path) of binary tree. 💡 Solution: Calculate height recursively At each node: diameter = max(diameter, left + right) Return height for parent 🎯 The Insight: Diameter at any node = left height + right height. Calculate height, update diameter as side effect. 📊 Complexity: O(n) time, O(h) space Day 72. One pass, two results. 🌳 #100DaysOfCode #DSA #LeetCode #Day72 #Java #TreeDiameter #HeightCalculation Height calculation = diameter found! 🌳✨
To view or add a comment, sign in
-
-
🔢 Day 67/100: Convert to Hex - Bit Masking Day 67. Convert integer to hex. Labeled "EASY." Actually easy this time. ✅ 📌 Problem: Convert number to hexadecimal string. 💡 Solution: & 15 → Get last 4 bits (0-15) Map to hex char (0-9, a-f) >>> 4 → Shift right 4 bits Repeat, reverse result 🎯 The Key: num & 15 extracts last hex digit. num >>>= 4 moves to next digit. 📊 Complexity: O(1) - at most 8 hex digits Day 67. Bit manipulation ftw. 💪 #100DaysOfCode #DSA #LeetCode #Day67 #Java #HexConversion #BitManipulation
To view or add a comment, sign in
-
-
🔢 Day 74/100: Largest Number - Custom Sort Trick Day 74. Form largest number from array. Custom comparator does the magic. ✅ 📌 Problem: Arrange numbers to form the largest possible number. Example: [3,30,34,5,9] → "9534330" 💡 Solution: Convert to strings Sort with custom rule: Compare (a+b) vs (b+a) "30"+"3" = "303" "3"+"30" = "330" "330" > "303" → "3" comes first 🎯 The Insight: Don't sort by value. Sort by "which concatenation is larger?" Edge case: All zeros → return "0" 📊 Complexity: O(n log n) time Day 74. String sorting solved. 🔢 #100DaysOfCode #DSA #LeetCode #Day74 #Java #LargestNumber #CustomSort
To view or add a comment, sign in
-
-
Day 17 - Container With Most Water Technique Used: Two-Pointer Optimization Key Idea: Initialized pointers at both ends of the array and computed the area using min(height[left], height[right]) × (right - left). Moved the pointer at the smaller height inward to potentially increase the area. Time Complexity: O(n) #Day17 #LeetCode #Java #TwoPointers #DSA
To view or add a comment, sign in
-
-
🔲 Day 69/100: Set Matrix Zeroes - Mark First, Set Later Day 69. Matrix problem. Can't set zeros while finding them. Two-pass solution. ✅ 📌 Problem: If element is 0, set its entire row and column to 0. 💡 Solution: Pass 1: Mark which rows/cols have 0s Pass 2: Set marked rows to 0 Pass 3: Set marked cols to 0 🎯 The Trap: If you set 0s immediately, you'll create new 0s and mess up the logic! Track first, modify later. 📊 Complexity: O(m×n) time, O(m+n) space Day 69. Matrix manipulation. 🔲 #100DaysOfCode #DSA #LeetCode #Day69 #Java #MatrixZeroes #TwoPass
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development