Incrementing Large Integer Array by One

🚀 Day 17/30– DSA Challenge 📌 LeetCode Problem – Plus One 📝 Problem Statement You are given a large integer represented as an array of digits. Increment the integer by one and return the resulting array. 📌 Example Input: digits = [1,2,3] Output: [1,2,4] 📌 Edge Case Input: [9,9,9] Output: [1,0,0,0] 💡 Key Insight Addition starts from the last digit. 👉 If digit < 9 → just add 1 and return 👉 If digit == 9 → it becomes 0 and carry moves left If all digits are 9 → create a new array. 🚀 Algorithm 1️⃣ Traverse from right → left 2️⃣ If digit < 9: Increment it Return array 3️⃣ Else: Set digit = 0 Continue 4️⃣ If loop ends → all were 9 Create new array of size n+1 Set first element = 1 ✅ Java Code (Optimal O(n)) class Solution { public int[] plusOne(int[] digits) { for (int i = digits.length - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } // All digits were 9 int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) (except edge case) 📚 Key Learnings – Day 17 ✔ Handle carry carefully ✔ Think from right to left ✔ Edge cases matter more than logic here ✔ Small problems test attention to detail Simple idea. Tricky edge case. Clean implementation. Day 17 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories