Facebook Interview Question


Country: United States




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

Visit AONECODE.COM for ONE-ON-ONE private lessons by FB, Google and Uber engineers!

SYSTEM DESIGN Courses (highly recommended for candidates of FB, LinkedIn, Amazon, Google and Uber etc.),
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algorithms, Clean Coding),
latest interview questions sorted by companies,
mock interviews.

Our students got hired from G, U, FB, Amazon, LinkedIn, MS and other top-tier companies after weeks of training.

Email us aonecoding@gmail.com with any questions. Thanks!

SOLUTION:

public void nextPermutation(int[] nums) {
        if(nums.length <= 1)  return;

        int i = nums.length - 1;
        while(i >= 1 && nums[i] <= nums[i-1]) i--; //find first number which is smaller than it's after number
        if(i!=0) swap(nums,i-1); //if the number exist,which means that the nums not like{5,4,3,2,1}
        reverse(nums,i);
    }

    private void swap(int[] a,int i){
        for(int j = a.length - 1;j > i;j--){
            if(a[j] > a[i]){
                int t = a[j];
                a[j] = a[i];
                a[i] = t;
                break;
            }
        }
    }

    private void reverse(int[] a,int i){//reverse the number after the number we have found
        int first = i;
        int last = a.length - 1;
        while(first<last){
            int t = a[first];
            a[first] = a[last];
            a[last] = t;
            first++;
            last--;
        }
    }

- jojocat1010 May 13, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Looks like your method will take int array. But in the above problem it says int number. How does it work ?

- sarunreddy82 May 15, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def next_permutation(x):
 v=list(str(x))
 n=len(v)
 vr=[]
 if n>1:
  for i in range(1,n):
   pc=v[-1*i]
   pn=v[-1*(i+1)]
   if pc>pn:
     vr.append(pc)
     vr.sort()
     for j in vr:
       if j>pn:
         vr.append(str(pn))
         vr.sort()
         v[-1*(i+1)]=str(j)
         vr.remove(str(j))
         for counter in range(0, len(vr)):
            z=vr[0]
            v[-1*(i+1)+1+counter]=z
            vr.remove(z)
         x=''.join(v)
         x=int(x) 
         return x
   else:
     vr.append(str(pc))
 return x

- Sri V June 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def smallest_greater_perm(x):
smallest_perm=0
list_digits=[]
while x>0:
list_digits.append(x % 10)
x//=10
if x==0: break
if list_digits==sorted(list_digits): return print('No greater permutation exists')
else:
for i,item in enumerate(list_digits):
if item < list_digits[0]:
list_digits[0],list_digits[i]=list_digits[i],list_digits[0]
break
for i,item in enumerate(list_digits):
smallest_perm+=item*10**i
return smallest_perm

- E2themacs June 16, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void findNextPermutation(char[] numArr) {
if(numArr.length == 0) {
return;
}
// Find the max i, so that K(i-1) < ki
// Find the max j, so that K(i-1) < kj
// Swap Ki and K(i-1)
// reverse from Ki, ki+1.... kn;
int i = numArr.length -2;
while(i >=0 && numArr[i+1] <= numArr[i]) {
i--;
}
if(i >=0) {
int j = numArr.length -1;
while(j >=0 && numArr[j] <= numArr[i]) {
j--;
}
swap(numArr, i, j);
}
reverse(numArr, i+1);

for(char c : numArr) {
System.out.print(c + ", ");
}
}

private static void reverse(char[] numArr, int start) {

int i = start; int j = numArr.length -1;
while(i <j) {
swap(numArr,i,j);
i++;
j--;
}
}

private static void swap(char[] numArr, int i, int j) {
char temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}

- sarunreddy82 June 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Permutation {
	public static void main(String[] args) {
		int num = 231145;
		permutation(num);
	}

	public static void permutation(int num) {
		List<String> tokenize = new ArrayList<String>();
		while (num > 0) {
			tokenize.add(String.valueOf(num % 10));
			num /= 10;
		}

		String[] sortedArr = tokenize.toArray(new String[0]);
		Arrays.sort(sortedArr);
		System.out.println();
		for (int i = 1; i < sortedArr.length; i++) {
			if (!sortedArr[i].equals(sortedArr[i - 1])) {
				String swap = sortedArr[i];
				sortedArr[i] = sortedArr[i - 1];
				sortedArr[i - 1] = swap;
				break;
			}
		}

		for (int i = sortedArr.length-1; i >= 0; i--) {
			System.out.print(sortedArr[i]);
		}

	}

}

- Sumit Dang August 02, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void nextPermutation(int[] a) {
    int n = a.length;

    int i = n - 1;
    while(i-1 >= 0 && a[i-1] >= a[i]) i--;  // Find the smallest i where  a[i..n-1] is reverse sorted

    if(i != 0) {                           // if i == 0, the input is largest permutation, so just need to sort array
        int j = n - 1;
        while(a[i-1] >= a[j]) j--;         // find the smallest j where a[i-1] < a[j]

        swap(a, i-1, j);                  // swap a[i-1] and a[j]
    }

    Arrays.sort(a, i, n);                  // sort a[i-1..n-1]
}

void swap(int[] a, int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

- Shail August 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void nextPermutation(int[] a) {
    int n = a.length;

    int i = n - 1;
    while(i-1 >= 0 && a[i-1] >= a[i]) i--;  // Find the smallest i where  a[i..n-1] is reverse sorted

    if(i != 0) {                           // if i == 0, the input is largest permutation, so just need to sort array
        int j = n - 1;
        while(a[i-1] >= a[j]) j--;         // find the smallest j where a[i-1] < a[j]

        swap(a, i-1, j);                  // swap a[i-1] and a[j]
    }

    Arrays.sort(a, i, n);                  // sort a[i-1..n-1]
}

void swap(int[] a, int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

- Shail August 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n log n) solution in C++ using DP.

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

vector<int> digits;

const int INF = 1e8;

vector<vector<pair<int, int>>> value;
pair<int, int> larger(int d, int i) {
    auto & res = value[d][i];
    if(res.first != -1) {
        return res;
    }
    if(i >= digits.size()) {
        return res = {INF, -1};
    }
    auto p = larger(d, i+1);
    if(digits[i+1] > d && digits[i+1] < p.first) {
        return res = {digits[i+1], i+1};
    }
    return res = p;
}

void debug() {
    for( int d : digits ) {
        cout << d << " ";
    }
    cout << '\n';
}

bool next_permutation(int i) {
    if(i >= digits.size()) {
        return false;
    }
    value.assign(10, vector<pair<int,int>>(digits.size()+2, {-1, -1}));
    auto p = larger(digits[i], i);
    if(p.second != -1) {

        swap(digits[i], digits[p.second]);

        sort(digits.begin()+i+1, digits.end());
        return true;
    }
    return false;
}

bool next_permutation() {
    for(int i = digits.size() -1; i >= 0; --i) {
        if(next_permutation(i)) return true;
    }
    return false;
}

int main() {

    digits = {3, 4, 1, 5, 2};

    while(next_permutation()) {
        for( int d : digits ) {
            cout << d << " ";
        }
        cout << '\n';
    }
    return 0;
}

- Kappa August 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from bisect import bisect_right, insort

def next_smallest_permutation(n):
    ns = str(n)
    l = len(ns)
    arr = [ns[-1]]
    for i in range(l-2, -1, -1):
        insort(arr, ns[i])
        if ns[i] < ns[i+1]:
            j = bisect_right(arr, ns[i])
            anss = ns[:i] + arr[j] + ''.join(arr[:j]) + ''.join(arr[j+1:])
            return int(anss)
    #Retuns the rolled over permutation i.e smallest parmutation if it is already the largest
    return ''.join(arr)

# Tests
print(next_smallest_permutation(825))
print(next_smallest_permutation(82552))
print(next_smallest_permutation(95432))

- anoophallur September 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int nextPer(int num) {

        int[] arr= numToArr(num);
        int lastSwap=0;
        for(int i=arr.length-1;i>lastSwap;i--){
            for(int j=i;j>lastSwap;j--){
                if(arr[i]>arr[j]){
                    swap(arr,j,i);
                    lastSwap=j;
                }
            }
        }

        return arrToNum(arr);

    }

- brachipackter October 03, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package practice2018;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NextPermutation {
	public static void main(String[] args){
		String[][] testcases = {
				{"12", "21"},
				{"315","351"},
				{"583","835"},
				{"12389","12398"},
				{"34722641","34724126"}
		};
	   for(int i = 0; i < testcases.length; i++){
		   try {
			   String actual = next(testcases[i][0]);
			   System.out.println("test " + testcases[i][0] + " actual " + testcases[i][1] + " " + actual);
		   } catch (Exception e){
			   System.out.println("test " + testcases[i][0] + " " + e.getMessage());
		   }
	   }
   }
   
   public static String next(String inp) throws Exception {
	   char[] digits = inp.toCharArray();
	   int n = digits.length;
	   
	   for (int i = n-1; i> 0; i--){
		   if(digits[i-1] < digits[i]){
			   // find immediate next permutation for substring(digits,i-1)
			   List<Character> a = new ArrayList<Character>();
			   for (int j = i-1; j < n; j++){
				   a.add(digits[j]);
			   }
			   Collections.sort(a);
			   
			   // find smallest digit larger than digits[i-1] in digits[i, ..]
			   String partial = "";
			   for (int j = 0; j < a.size(); j++){
				   if (a.get(j) > digits[i-1]){
					   partial += a.get(j);
					   
					   for (int k = 0; k < a.size(); k++){
						   if (k != j){
							   partial += a.get(k);
						   }
					   }
					   break;
				   }
			   }
			   
			   String result = "";
			   for (int j = 0; j < i-1; j++){
				   result += digits[j];
			   }
			   result += partial;
			   return result;
		   }
	   }
	   throw new Exception("At maximum, cannt find next");
   }
}

- just_do_it November 10, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

int greater(int num)
{
	string str = to_string(num);
	int n = str.size();
	int i = 0, j=0;
	
	for(i=n-1; i>-1; i--)
	{
		for (j=i-1; j>-1; j--)
		{
			if (str[i] > str[j])
			{
				str = str.substr(0, j) + str[i] + str.substr(j, i - j) + str.substr(i+1, n-(i+1));
				sort(str.begin() + j + 1, str.end());
				return stoi(str);
			}
		}
	}
	return -1;
}

- aman.bansal4u May 18, 2018 | 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