Hi,
I was looking at the Java solution for Problem 6.2 from the 1.4.5 edition of the book(Link to solution in reply below) .
This walks over the list fully 2 times when doing 2 reverses.
I came up with this solution which walks over the list only once:
public class PlusOne {
public List<Integer> plusOne(List<Integer> A) {
int n = A.size()-1;
A.set(n, A.get(n) + 1);
for(int i=n; i>0 && (A.get(i) == 10); i--) {
A.set(i - 1, A.get(i - 1) + 1);
A.set(i, 0);
}
if (A.get(0) == 10) {
A.set(0, 0);
A.add(0,1);
}
return A;
}
}
Since List.add() has constant amortized cost according to the documentation, adding an element to the head of the list would be constant time. Hence I walk over the list in reverse and if 0th element is 10, I make it 0 and add 1 to the head of the list.
Is my implementation correct/efficient?