LeetCode Challenge: Plus One
Time for another LeetCode challenge! This week, I tackled the Plus One challenge. This challenge called to build a function that would receive an array made up of numbers. The function would output an array that adds one to the integer that the original array represents. For example, if the passed-in array is [1, 2, 3], the returned output would be [1, 2, 4]. If the passed-in array is [5, 3, 9], the returned array would be [5, 4, 0].
Through testing these methods in my Chrome browser’s console, I quickly found that I had forgotten that when an array is joined through the join method, it’s returned as a string instead of an integer. This is easily remedied by using parseInt to convert the string into an integer. After I had the integer from the original array, all I had to do was add one to the number, then turn that integer back into a string and split it apart.
This solution passes the example cases given in the challenge, but when it’s submitted there are still a number of tests failing! Digging into the information, I saw that when the digits array was beyond nineteen digits, the parseInt line was turning every number past that point into zeroes. I had to find an alternative method that would allow me to maintain those numbers beyond the nineteenth digit.
After the integer variable was created, I had to take that new integer and convert it back into a string so it could be converted back into an array, which would be the returned value to finish off the function.
There it is! This function passes all tests, let’s check out the runtime.
Very solid. This function works as O(n) linear time, so it’s an efficient function when it comes to time complexity. The space complexity likely leaves something to be desired, since it’s saving variables of large values of data, but that’s a problem that can be solved another day.