Google Interview Question for Software Developers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
4
of 4 vote

private ArrayList<Integer> increment(ArrayList<Integer> number) {
	int carry = 1;
	for(int i=number.size()-1;i>=0 && carry!=0;i--) {
		carry = number.get(i) + carry;
		number.set(i, carry%10);
		carry = carry/10;
	}
	if(carry>0) {
		number.add(0, carry);
	}
	return number;
}

- Invincible July 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int[] increment(int[] arr){
		int i =arr.length-1;
		if(arr[0]>=0){
			while(true){
				if(i==0 || arr[i]!=9){
					arr[i]+=1;
					return arr;
				}
				arr[i--]=0;
			}	
		}
		while(true){
			if(i==0){
				arr[i]+=1;
				return arr;
			}
			if(arr[i]!=0){
				arr[i]-=1;
				return arr;
			}
			arr[i--]=9;
		}
		
	}

- infinity July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

public class IncrementIntegerAsArray {

	public static void main(String[] args) {
		int[] number = {1, 2, 3};

		for (int i = 0; i < 876; i++) {
			increment(number);
		}

        System.out.println(Arrays.toString(number));

        increment(number);
    }

	public static void increment(int[] number) {
		increment0(number, number.length - 1);
	}

	public static void increment0(int[] number, int position) {
		if (position < 0) {
			throw new IllegalArgumentException();
		}

		if (number[position] < 9) {
			number[position]++;
		} else {
			number[position] = 0;
			increment0(number, position - 1);
		}
	}
}

- damluar July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Input {1,2,3} is just an example. The solution won't work for input {9}, {9,9}, ...

- undefined July 30, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The solution increments a given number if it can be incremented. If passed array is too small, exception is thrown which I think make sense. So instead of passing {9} or {9,9} pass {0,9} or {0,0,9}.

- damluar August 04, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void incrementInt(char cArr[SIZE])
{
	int j = 0;
	for(int i=SIZE-1;i>=0;i--)
	{
		j =cArr[i]-'0';
		if(j<9)
		{
			cArr[i]=j+1+'0';
			break;
		}
		else
		{
			cArr[i]='0';
			continue;
		}
	}
}

- sv July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

start from first index, move towards end, keep a flag which will tell if all the numbers are 9 or not,
we will stop at end, and see if the flag is true, if no, we increment the number and if it goes to 10, we set it to 0 and move back with 1,
if the flag is true, we increase the size of the array by one, and set all the numbers to 0 except first one, we set that to 1.

- sonesh July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Firstly reverse the array
eg. arr = {1,2,3}
reversed array = {3,2,1}
2. add 1 to first element of reversed array and propagate carry accordingly

3. reverse the array to get actual array

eg. {9,9,9}

reversed array : {9,9,9}
adding 1 to first element
array after adding 1 : {0,0,0,1}
resultant array : {1,0,0,0}

O(n) complexity
Note: this can be done when there is sufficient space at the end of array.

- Source July 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class IncrementSvc
{
	public int[] increment(int[] a) throws NullPointerException
	{
	 	if(a==null)
		{
			throw new NullPointerException("input cannot be null");
		}
		int carry=1;
		for(int i=a.length-1;i>0;i--)
		{
			int total=a[i]+carry;
			carry=total/10;
			a[i]=total%10;
			
		}
		if(a[0]>9)
		{
			int[] result=new int[a.length+1];
			result[0]=a[0]/10;
			result[1]=a[0]%10;
			for(int i=2; i< result.length;i++)
			{
				result[i]=a[i-1];
			}
			a=result;
		}
		return a;
}

//Time:O(n) , Space: O(n).

- divm01986 July 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time O(n), Space O(n)

public static int[] IncArray(int[] arr) {
        int carryOver = 0;
        for(int i = arr.length - 1; i >= 0; i--) {
            arr[i]++;
            arr[i] += carryOver;
            carryOver = 0;

            if(arr[i] >= 10) {
                carryOver = 1;
                arr[i] %= 10;
            } else {
                break;
            }

        }

        int[] result = arr;
        if(carryOver == 1) {
            result = new int[arr.length + 1];
            result[0] = 1;
            System.arraycopy(arr, 0, result, 1, arr.length);
        }

        return result;
    }

- Dave July 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ArrayAsInteger {
    public int[] increment(int[] array) {
        int[] incrementedArray = incrementByOne(array, array.length - 1);
        return (array[0] < 10) ? incrementedArray : extendedBoundary(array.length + 1);
    }

    private int[] extendedBoundary(int length) {
        int[] array = new int[length];
        array[0] = 1;
        return array;
    }

    private int[] incrementByOne(int[] array, int i) {
        array[i] = array[i] + 1;
        if (array[i] >= 10 && i > 0) array[i] = array[i] % 10;
        else return array;
        return incrementByOne(array, i - 1);
    }
}

git.io/vYLy8 -- source
git.io/vYLyL -- test

- inadram July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void convert(int[] _sample){
int i=0;
_sample.toString();
String _convert=null;
StringBuilder build = new StringBuilder();
for(i=0;i<_sample.length;i++){
	build.append(_sample[i]);
}
int _convertedVal=Integer.parseInt(build.toString());	
_convertedVal=_convertedVal+1;
String _back=Integer.toString(_convertedVal);
int[] _finalVal = new int[_back.length()];
for(i=0;i<_back.length();i++){
	_finalVal[i]=Integer.valueOf(String.valueOf(_back.charAt(i)));
	System.out.println("The "+i+" element is "+_finalVal[i]);
}

}

- Anonymous July 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void convert(int[] _sample){
int i=0;
_sample.toString();
String _convert=null;
StringBuilder build = new StringBuilder();
for(i=0;i<_sample.length;i++){
	build.append(_sample[i]);
}
int _convertedVal=Integer.parseInt(build.toString());	
_convertedVal=_convertedVal+1;
String _back=Integer.toString(_convertedVal);
int[] _finalVal = new int[_back.length()];
for(i=0;i<_back.length();i++){
	_finalVal[i]=Integer.valueOf(String.valueOf(_back.charAt(i)));
	System.out.println("The "+i+" element is "+_finalVal[i]);
}


	

}

- Vikram July 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public List<Integer> incrementNumber(List<Integer> list) {
		List<Integer> ans = new ArrayList<Integer>();
		int num = 0;

		for (Integer i : list) {
			num = (num + i) * 10;

		}

		num /= 10;
		System.out.println(num);
		num++;
		String s = Integer.toString(num);
		for (int i = 0; i < s.length(); i++) {
			ans.add((s.charAt(i) - '0') % 10);
			num /= 10;
		}
		return ans;
	}

- dheeraj2311 July 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void Increment(int[] a)
{
	int index = a.Length - 1;
	bool carry = true;

	while (carry && index >=0)
	{
		a[index]++;
		carry = a[index] % 10 == 0;
		if (carry)
		{
			a[index] = 0;
			index--;
		}
	}

	// Optional if we want to spin the values
	if (carry && index < 0)
		a[a.Length - 1] = 1;
}

- hnatsu July 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Node.js

var intArray = [1,2,3];
var int = Number(intArray.join(""));
int++;
int = int + "";
console.log(int.split(""));

- brazilcoder August 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Node.js (without parsing to int):

var intArray = [1,9,9];
var carryOver = 0;
for (var i = 0; i < intArray.length; i++) {
    intArray[i] += 1 + carryOver;
    if (intArray[i] > 9) {
        intArray[i] = 0;
        carryOver = 1;
    }
    else {
        carryOver = 1;
    }
}
console.log(intArray); // [ 2, 0, 0 ]

- brazilcoder August 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

It must have been 3 curly braces, sorry.

static int[] increment(int[] a )
    {
       int sum = 1; 
       int p = 0;
       for(int i= a.length-1; i>=0; i--)
       {
         sum = sum+a[i]*(int)Math.pow(10,p);  
         p++;
       }
       p--;
       System.out.format("%n %d %n %d ",sum,p); 
       for(int j = 0; j<a.length;j++)
       { 
          int entre = (int)Math.pow(10, p);
          System.out.format("--entre %d  sum %d %n",entre, sum );
          int temp  = sum/ entre;
          a[j]= temp;
          int rem = sum%entre;
          System.out.format("reminder %d ",rem);
          sum = rem;
          System.out.format("temp %d %n",temp);
          p--;
       }
       
        System.out.format("%s %n",Arrays.toString(a));
      
      return a;
    }

- josearturodelosangeles August 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My first response would definitely just be (in javascript)

return (parseInt(arr.join('')) + 1).toString().split(''))

Don't reinvent the wheel

- Nick August 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void incrementArray(int arr[]) {
	for(int i=arr.length()-1; i>=0; --i) {
		++arr[i];
		if(arr[i]) break	
	}
}

- Josh August 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void addOne( ArrayList a, int idx, int carry ){
	if(idx<0) {
		if(carry != 0) a.add(0, carry);
		return;
	}
	int val = (int)a.get(idx) + carry;
	a.set(idx, val%10);
	addOne(a, idx-1, val/10);
}

calles as addOne(a, a.size()-1, 1)

- noname September 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time: worst is O(n), only if all digits are 9; avg is much smaller - O(k), where k is the number of last digits in a row that are 9
Space: O(1) (it's not totally clear if they want a new array, but it sounds like incrementing in-place is okay)

def increment_array(a)
  i = a.size - 1

  while i >= 0 && a[i] == 9
    a[i] = 0
    i -= 1
  end

  if i < 0
    a.unshift(1)
  else
    a[i] += 1
  end

  a
end

- Brian September 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

# Increment an integer in an array

def incr_list(list):
    n = len(list)
    if n == 0:
        return
    index = n - 1
    while index >= 0:
        sum = list[index] + 1
        if sum < 10:
            list[index] = sum
            return
        else:
            list[index] = 0
        index -= 1
            
    list.insert(0, 1)
    
if __name__ == "__main__":
    list = [9,9,9,9]
    incr_list(list)
    print list

- techreader September 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] intAsArray = {1, 2, 9};

        String intStr = "";
        for (int i=0; i<intAsArray.length; i++) {
            intStr += intAsArray[i];
        }

        int intIncrementedAsInt = Integer.parseInt(intStr) + 1;
        String intIncrementedAsString = String.valueOf(intIncrementedAsInt);
        int[] intIncrementedAsArray = new int[intIncrementedAsString.length()];

        for (int i=0; i<intIncrementedAsString.length(); i++) {
            intIncrementedAsArray[i] = Integer.valueOf(""+intIncrementedAsString.charAt(i));
        }

        System.out.println(Arrays.toString(intIncrementedAsArray));

- Mark September 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] intAsArray = {1, 2, 9};

        String intStr = "";
        for (int i=0; i<intAsArray.length; i++) {
            intStr += intAsArray[i];
        }

        int intIncrementedAsInt = Integer.parseInt(intStr) + 1;
        String intIncrementedAsString = String.valueOf(intIncrementedAsInt);
        int[] intIncrementedAsArray = new int[intIncrementedAsString.length()];

        for (int i=0; i<intIncrementedAsString.length(); i++) {
            intIncrementedAsArray[i] = Integer.valueOf(""+intIncrementedAsString.charAt(i));
        }

        System.out.println(Arrays.toString(intIncrementedAsArray));

- Mark September 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def increment(l):
    for i in range(len(l) - 1, -1, -1):
        l[i] += 1
        if l[i] < 10:
            break
        l[i] %= 10
    return l

- encoded October 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Please judge this.

int main(){

    vector<int> vec;

    for(int i = 1; i<10; i++){
        vec.push_back(i);
    }

    int temp;
    if(vec[vec.size() -1] + 1 >= 10){
        temp = vec[vec.size() -1] + 1 > 10;
        vec[vec.size() -1] = 1;
        vec.push_back(temp % 10);
    }

    for(int i = 0; i<vec.size(); i++){
        cout << vec[i] << "\n";
    }

    return 1;

}

- pukumar21985 August 13, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More