I need advice on my ruby based solution to a problem on Interviewbit. The problem is as follows
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list. There can be upto 10,000 digits in the input array.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
My first solution was as follows
def plusOne(a)
new_number = a.join.to_i + 1
result = []
while new_number > 0
result.push new_number%10
new_number /= 10
end
result.reverse
end
This algorithm seems correct, it passed the test inputs but on submission it gives a 'Time Limit Exceeded'. My second solution was a successful submission and is as follows.
def plusOne(a)
carry = 1
start_index = a.size - 1
temp_result = []
ans = []
for i in start_index.downto(0)
sum = a[i] + carry
carry = sum/10
temp_result.push sum%10
end
temp_result.push carry
start_index = temp_result.size - 1
while start_index >= 0 and temp_result[start_index] == 0
start_index -= 1
end
while start_index >= 0
ans.push temp_result[start_index]
start_index -= 1
end
ans
end
My first solution seems to be O(n) to me as we are just iterating over the digits in the number. So, can someone please tell me why it could have exceeded the time limit ?
Thank You
Integer#digits
returns the least significant digit at the head of the array. – Eric Duminil 19 hours ago