How to prepare for your next Coding Interview
Here are some tips while preparing for your coding interviews. 1. Do study or…
September 03, 2020
Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example
Input: digits = [1,2,3]
Output: [1,2,4]
It has very simple solution, just by iterating array from the end. And, keeping track of carry.
A simple complexity here is that result can be bigger than original array if we got a carry for the last sum.
public int[] plusOne(int[] digits) {
int l = digits.length;
//initializing carry with the number we want to add for first time.
int carry = 1;
for (int i=l-1; i>=0; i--) {
digits[i] = digits[i] + carry;
carry = digits[i]/10;
digits[i] = digits[i]%10;
}
// copy result to another array
int targetSize = carry == 1 ? l+1 : l;
int[] res = new int[targetSize];
int i=0;
if (carry == 1) {
res[0] = carry;
i = 1;
}
for (; i<targetSize; i++) {
res[i] = digits[i-carry];
}
return res;
}
Its O(n)
Here are some tips while preparing for your coding interviews. 1. Do study or…
Sorting Problems Merge Sort Quick Sort Heap Sort Bubble Sort Selection Sort…
** Inversion There is an array(a) and two indexes i and j. Inversion is the…
Young Tableau A a X b matrix is Young Tableau if all rows(from left to right…
First try to understand question. Its a binary tree, not a binary search tree…
A Binary Search tree (BST) is a data structure which has two children nodes…
Introduction In this post we will see following: How to schedule a job on cron…
Introduction There are some cases, where I need another git repository while…
Introduction In this post, we will see how to fetch multiple credentials and…
Introduction I have an automation script, that I want to run on different…
Introduction I had to write a CICD system for one of our project. I had to…
Introduction Java log4j has many ways to initialize and append the desired…