DEV Community

vc7
vc7

Posted on • Edited on

1

LeetCode in Swift - 66. Plus One

Problem

Data Structure

  • Array

Intuition

  • Travel through from the last item.

Routine

  • If number is less than 9, plus 1 then return the digits
    • The last digit (1st step):
      • Initial plus 1
    • Other digits:
      • Carry from the digit on the right (index + 1)
    • Early exist: No need to carry to the next digit, can early exist.
  • If number is >= 9 means needed to carry
    • Set to 0
    • Continue

End of routine

When go through every digits without return, means we have a carry from the highest digit, so that we have to insert a 1 to the digits[0]

Code

class Solution {
    func plusOne(_ digits: [Int]) -> [Int] {
        var index = digits.count - 1
        var digits = digits

        while index >= 0 {
            if digits[index] < 9 {
                digits[index] += 1
                return digits
            }
            digits[index] = 0
            index -= 1
        }

        digits.insert(1, at: 0)
        return digits
    }
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time Complexity: O(n)
    • Linear travel of the array.
  • Space Complexity: O(n)
    • * Need to copy an array for mutable purpose. If not consider this can be O(1)

End of post

That's it!

Please leave comment if you have any comments, thanks for your reading!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay