Facebook Interview Question for Interns


Country: United States




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

```
def helper(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
next_=[1]
i=0
digits=digits[::-1]
j=0
cur=0
res=[]
while(i<len(next_) or j<len(digits)):
first = next_[i] if i<len(next_) else 0
i+=1
second = digits[j] if j<len(digits) else 0
j+=1
sum_=first+second+cur
res.append(sum_%10)
cur=sum_/10
if cur:
res.append(1)
return res[::-1]
```

- mehdi January 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class NextInteger {

    public static void main(String[] args) {
        System.out.print("Next Integer: " + Arrays.toString(nextInteger(new int[]{9, 9, 8})));
    }

    private static int[] nextInteger(int[] input) {
        if (input.length == 0) {
            return input;
        }
        int sum;
        int carry = 1;
        for (int i = input.length - 1; i >= 0 && carry != 0; i--) {
            sum = input[i] + carry;
            input[i] = sum > 9 ? sum - 10 : sum;
            carry = sum > 9 ? 1 : 0;
        }
        if (carry == 0) {
            return input;
        }
        int[] result = new int[input.length + 1];
        result[0] = carry;
        System.arraycopy(input, 0, result, 1, input.length);
        return result;
    }
}

- duenytz January 22, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

dsfmm

- Rimsha Maredia January 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def helper( digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
next_=[1]
i=0
digits=digits[::-1]
j=0
cur=0
res=[]
while(i<len(next_) or j<len(digits)):
first = next_[i] if i<len(next_) else 0
i+=1
second = digits[j] if j<len(digits) else 0
j+=1
sum_=first+second+cur
res.append(sum_%10)
cur=sum_/10
if cur:
res.append(1)
return res[::-1]

- Mehdi January 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findNextInteger(int[] arr) {

		if (arr == null || arr.length == 0)
			return 0;
		int number = 0;
		
		// 10^2*1+10^1*2+10^0*3 = 100+20+3 = 234
		for (int i = arr.length - 1, j = 0; i >= 0 && j <= arr.length - 1; i--, j++) {
			number = number + (int) (Math.pow(10, i) * arr[j]);
		}
		return (number+1);
	}

- sanjos January 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

u shud return array, not integer

- VB January 26, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def nextNum(nums):
i = len(nums)
inc = 1
for a in range(i, 0, -1):
num = nums[a-1]+inc
inc = num/10
nums[a-1] = num%10
return nums

- Gordon January 18, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{var interger = [1,9,9]
let c = interger.count-1
var carryforward = 0
for n in 0...c{
var temp = interger[c-n]
temp = temp + 1
if temp == 10{
carryforward = 1
temp = 0
interger[c-n] = temp
}else{
carryforward = 0
interger[c-n] = temp
break
}
}
if carryforward == 1{
interger.insert(1, at: 0)
}
print(interger)
}

- Anonymous January 20, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var NextInteger = function (arr) {
var carry = 0;
var result = [];
for (var i = arr.length - 1; i >= 0; i--) {
var sum = 0
var addNum = 0;
if (i == arr.length - 1) {
addNum = arr[i] + 1;
} else {
addNum = arr[i];
}
sum = carry + addNum;
if (sum > 9) {
carry = 1; sum = 0;
}
else {
carry = 0;
}
result.unshift(sum);
}

if (carry > 0)
result.unshift(carry);

}

- Narendra Patel January 21, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var arr = [1, 2, 3, 4, 5];
var number = 0;

for (var i = 0; i < arr.length; i++) {
	var power = arr.length - 1 - i;
	var multiplier = 10 ** power;
	number += arr[i] * multiplier;
}

console.log(number + 1);

- ik January 23, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var arr = [1, 2, 3, 4, 5];
var number = 0;

for (var i = 0; i < arr.length; i++) {
	var power = arr.length - 1 - i;
	var multiplier = 10 ** power;
	number += arr[i] * multiplier;
}

console.log(number + 1);

- ik2 January 23, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <algorithm>

void increment_num(std::vector<int>& v) {
 
	std::reverse(v.begin(), v.end());
  v[0] += 1; 
	if (v[0] == 10) {
		v[0] = 0;
		int carry = 1;
		for (int i=1; i<v.size();++i){
			v[i] += carry;
			carry = 0;
		  if (v[i] == 10){
				v[i] = 0;
				carry = 1;
			}	
		}
    if (carry){
			v.emplace_back(carry);
		}
  }

	std::reverse(v.begin(), v.end());
}

int main(){


	std::vector<int> v{9, 9, 9};

	increment_num(v);
	for (auto a: v) {
		std::cout << a << " ";
	}
	std::cout << std::endl;

	return EXIT_SUCCESS;
}

- Anonymous January 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x = [1, 2, 3]
x = [str(i) for i in x]
x = int(''.join(x)) + 1
x = [int(i) for i in str(x)]
print(x)

- Anonymous January 28, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*given an array representing a non-negative integer (ex: 123 represented as [1,2,3]), return the next integer (output: [1,2,4])
.run through all edge cases (ex: [9,9,9,9,9,9,9,9] etc)
*/
public class IncreasingArray {

public static void main(String args[])
{
int[] input=new int[]{9,9,9,9,9};

System.out.println("Next is ==>"+Arrays.toString(getNext(input)));

}


public static int[] getNext(int[] inputArr)
{

String inputArrStr = Arrays.toString(inputArr).replaceAll("\\[|\\]|,|\\s","");
int number = Integer.parseInt(inputArrStr);
number = number + 1;
String newNumber = String.valueOf(number);
char[] newNumberArr = newNumber.toCharArray();

int[] result = new int[newNumber.length()];

for(int i=0;i<=newNumber.length()-1;i++)
{
result[i]=Character.getNumericValue(newNumberArr[i]);
}

return result;

}

}

- Praveen January 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class IncreasingArray {

    public static void main(String args[])
    {
        int[] input=new int[]{9,9,9,9,9};
        System.out.println("Next is ==>"+Arrays.toString(getNext(input)));
    }


    public static int[] getNext(int[] inputArr)
    {
        String inputArrStr = Arrays.toString(inputArr).replaceAll("\\[|\\]|,|\\s","");

        int number = Integer.parseInt(inputArrStr);
        number = number + 1;
        String newNumber = String.valueOf(number);
        char[] newNumberArr = newNumber.toCharArray();

        int[] result = new int[newNumber.length()];

        for(int i=0;i<=newNumber.length()-1;i++)
        {
            result[i]=Character.getNumericValue(newNumberArr[i]);
        }

        return result;

    }
}

- Praveen January 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int[] GetNextArray(int[] input) 
        {
            var value = string.Join(string.Empty, input.Select(p => p.ToString()).ToArray());

            var str = (int.Parse(value) + 1).ToString();

            var output = new int[str.Length];

            for (var index = 0; index < str.Length; index++)
            {
                output[index] = int.Parse(str[index].ToString());
            }

            return output;
        }

- Elena January 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function nextInteger(A) {
  let cur = 1

  for (let i = A.length - 1; i >= 0; i -= 1) {
    let num = cur + A[i]
    let rem = num % 10
    cur = Math.floor(num / 10)
    A[i] = rem
  }

  if (cur > 0) return [cur].concat(A)
  return A
}

- 0x March 03, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function sayHello(A) {
  let sp  = A.join("");
  let num = parseInt(sp)+1;
  let str = num.toString();
  let arr = str.split("");
  for(let i = 0; i < arr.length; i++) {
   arr[i] = parseInt(arr[i]);
  }
  return arr;
}

- 0z April 15, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def cheat( some_arr ){
  some_num = 1 + fold( some_arr, 0 ) as {  $.p*10 + $.o }
  ret_arr = list()
  while ( some_num != 0 ){
    ret_arr.add( 0 , some_num % 10 )
    some_num /= 10 
  }
  ret_arr 
}
def non_cheat( some_arr ){
  resp = rfold ( some_arr, { 'carry' : 1, 'result' : list() } ) as {
    r = ( $.o +  $.p.carry )
    $.p.carry = r / 10 
    $.p.result.add ( 0,  r % 10 )
    $.p // return 
  }
  resp.result // return 
}

println( non_cheat( [1,4,3 ] ) )

- NoOne May 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

(parseInt(arrayOfElements.toString().replace(/,/g,'')) + 1).toString().split('');

- Fernando Castro May 10, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

ans = []
def next_int(arr, x):
    if x == len(t)-1:
        ss =  t[x]+1
        if ss > 9:
            ans.append(ss%10)
            return ss/10
        else:
            ans.append(ss)
            return 0

    child_sum = next_int(arr, x+1)
    s = arr[x] + child_sum
    if s > 9:
        ans.insert(0,int(s%10))
        s = s / 10
    else:
        ans.insert(0,int(s))
        s = 0

    return s



# t = [1,2]
# t  = [1,2,3]
t = [9,9,9,9,9,9,9,9,9,9]

ans.insert(0, int(next_int(t, 0)))

- Nelson Bassey September 30, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/******************************************************************************

Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
cout<<"Input=";

vector <int> vec={1,9,9};
for (int j=0; j<vec.size();j++){

cout<<vec[j]<<" ";
}
reverse(vec.begin(),vec.end());
int carry=0, carry_new=0;




cout<<endl;

for (int i=0; i<vec.size(); i++){

if (i==0){
carry=(vec[0]+1)/10;
cout<<"carryjjjj= "<<carry<<"--------"<<endl;
vec[0]=(vec[0]+1)%10;

}

else{
cout<<"i= "<<i<<" carry= "<<carry<<endl;
carry_new=(vec[i]+carry)/10;
vec[i]=(vec[i]+carry)%10;
carry=carry_new;
}



}

if (carry==1)
vec.push_back(carry);
reverse(vec.begin(),vec.end());
cout<<"output= ";
for (int j=0; j<vec.size();j++){

cout<<vec[j]<<" ";
}

cout<<endl;
return 0;
}

- pingakshya2008 December 10, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class HelloWorld{

public static void main(String []args){
int[] ar = getArray(new int[]{9,9,5,9,9,8}, 5);
for(int y: ar){
System.out.println(y);
}

}

private static int[] getArray(int[] ar, int ind){
if(ind < 0) {
int[] arr = new int[ar.length+1];
arr[0] = 1;
for(int i=0; i< ar.length; i++){
arr[i+1] = 0;
}
return arr;
}
ar[ind] += 1;
if(ar[ind] > 9){
ar[ind] = 0;
return getArray(ar, ind-1);
} else

return ar;
}
}

- lklk March 18, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I will give two solutions:
One using O(n) extra space:

std::vector<int> next_int(std::vector<int> myvector) {
    
    std::vector<int> result;
    std::vector<int>::reverse_iterator rit = myvector.rbegin();
  
    int sum = 0, acc = 1;
    for (; rit!= myvector.rend(); ++rit) {
        sum = *rit + acc;
        if (sum == 10) {
            result.push_back(0);
            acc = 1;
        } else {
            result.push_back(sum);
            acc = 0;
            ++rit;
            break;
        }
    }
    
    if (rit!= myvector.rend())
        for (; rit!= myvector.rend(); ++rit) {
            result.push_back(*rit);
        } else {
          if (acc)
            result.push_back(acc);
        }
      
    std::reverse(result.begin(), result.end());
    
    return result;
}

The next one, no extra space used:

void next_int(std::vector<int> &myvector) {
    
    std::vector<int> result;
    std::vector<int>::reverse_iterator rit = myvector.rbegin();
  
    int sum = 0, acc = 1;
    for (; rit!= myvector.rend(); ++rit) {
        sum = *rit + acc;
        if (sum == 10) {
            *rit = 0;
            acc = 1;
        } else {
            *rit = sum;
            acc = 0;
            ++rit;
            break;
        }
    }
    
    if (rit== myvector.rend() && acc) {
        auto it = myvector.begin();
        myvector.insert ( it , acc );
    }
}

- arturocu81 October 09, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Javascript:

`${parseFloat([9,8,7,6,5,9].join('')) + 1}`.split('').map(n => parseInt(n, 10))

- Albert Smith February 17, 2022 | 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