Facebook Interview Question for Software Engineers


Country: United States
Interview Type: Phone Interview




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

func wordsReversed(string: String) -> String {
    return string.components(separatedBy: " ").reversed().joined(separator: " ")
}

- tomkowz October 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
3
of 5 vote

return string.Join(" ", value.split(' ').Reverse());

- Henry May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

function reverse(str) {
  return str.split(' ').reverse().join(' ');
}

- Dinkleberg May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

Reverse all chars in the main string and then in each word. Can be done in-place.

- celicom May 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

String reverseWords(String wordString) {
		StringBuilder sb = new StringBuilder();
		String[] words = wordString.split(" ");
		for (int i = words.length - 1; i >= 0; i--) {
			sb.append(words[i]);
			sb.append(" ");
		}
		return sb.toString().trim();

	}

- verma82 May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 3 vote

This is how you get N/2 performance where N is a number of words.

String reverseWords(String str) {
        String[] tokens = str.split(" ");
        for (int first = 0, last = tokens.length - 1; first < last; first++, last--) {
            String swapStr = tokens[first];
            tokens[first] = tokens[last];
            tokens[last] = swapStr;
        }
        return String.join(" ", tokens);
    }

- ivan.malygin May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class Main {

	public static void main(String[] args) {
		String s = "Man bites dog";
		printReverseWords(s);
	}

	public static void printReverseWords(String s){
		String[] words = s.split(" ");
		Collections.reverse(Arrays.asList(words));
		System.out.println(String.join(" ", words));
	}
}

- settyblue June 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseWords {

	public static void main(String[] args) {
		System.out.println(reverseWords("Man bites dog"));
	}
	
	public static String reverseWords(String value) {
		if (value == null || value.equals("")) {
			return null;
		}
		
		String[] words = value.split(" ");
		StringBuilder sb = new StringBuilder();
		for (int i = words.length - 1; i >= 0; i--) {
			sb.append(words[i] + " ");
		}
		return sb.deleteCharAt(sb.length()-1).toString();
	}
}

- guilhebl May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverseStringNotWords(char *string)
{
  int length = strlen(string);
  int start = 0;
  int end = 0;
  int mid = 0;

  for (int i=0; i<=length; i++) {
    if (string[i] == ' ' || string[i] == '\0') {
      end = i-1;
      mid = (end - start) / 2;
      for (int j=0; j<=mid; j++) {
        string[start+j]=string[start+j]^string[end-j]^(string[end-j]=string[start+j]);
      }

      start = i+1;
      if (string[i] == '\0')
        break;
    }
  }

  mid = length/2;
  length--;
  for (int j=0; j<mid; j++) {
    string[j]=string[j]^string[length-j]^(string[length-j]=string[j]);
  }

}

- periask May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverse(String value) {
    String newStr = "";
    String[] wordList = value.split(" ");
    for (int i=0; i<wordList.length; i++) {
      String space = i < wordList.length - 1 ? " " : "";
      newStr += wordList[wordList.length-1-i] + space;
    }
    return newStr;
  }

- tubofhoney May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;
class Reverse
{
public static void main(String args[])
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();

String arr[] = str.split(" ");
int len = arr.length;
StringBuffer result = new StringBuffer();
for(int i = len-1 ; i >= 0 ; i--)
{
result = result.append(arr[i]+" ");
}
String res = ""+result;
System.out.println(res);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

- Narendrakoli4666 May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Using string.Split method this requires O(N) space where N = number of words;
public string ReverseWords(string s)
{
	if (string.IsNullOrEmpty(s))
		return string.Empty;

	var arr = s.Split(' ');
	var sb = new StringBuilder();

	for (int i = arr.Length - 1; i > 0; i--)
		sb.Append(arr[i]).Append(" ");

	sb.Append(arr[0]);

	return sb.ToString();
}

// Implementing my own code to split the words
public string ReverseWords(string s)
{
	if (string.IsNullOrEmpty(s))
		return string.Empty;

	var sb = new StringBuilder();
	int i = s.Length - 1;
	int end = i;
	string word;

	while (i > 0)
	{
		if (s[i] == ' ')
		{
			word = s.Substring(i + 1, end - i);
			sb.Append(word);
			sb.Append(" ");
			end = i - 1;
		}

		i--;
	}

	word = s.Substring(0, end + 1);
	sb.Append(word);

	return sb.ToString();
}

- hnatsu May 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A simple C program which can convert the string in reverse

#include <stdio.h>

int main(int argc, char *argv[])
{
int i;
for(i=argc-1;i>0;i--)
printf("%s ",argv[i]);
return 0;
}

- shameerariff May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is in Objective C
#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
int i;
for(i=argc-1;i>0;i--)
NSLog(@"%s ",argv[i]);
return 0;
}

- shameerariff May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String reverseWords(String inStr){
String array[]=inStr.split(" ");

String outStr="";

for(int i=(array.length-1);i>=0;i--){

outStr+=array[i]+" ";

}

outStr=outStr.trim();
return outStr;


}

- Anonymous May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String reverseWords(String inStr){
String array[]=inStr.split(" ");

String outStr="";

for(int i=(array.length-1);i>=0;i--){

outStr+=array[i]+" ";

}

outStr=outStr.trim();

return outStr;

}

- vijay.lokhande.in May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I use Python:

t=input('Please enter a sentence: ')
tw=t.split(' ')
for i in range(len(tw)):
print(tw[len(tw)-1-i], end=' ')
print('\n')

- Anonymous May 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String reverseWord(String s) {
    StringBuilder sb = new StringBuilder();
    String[] sArray = s.split(" ");
        if(sArray > 0) {
        for(int i = sArray.length-1; i > 0; i--) {
            sb.append(sArray[i]).append(" ");
        }
        sb.append(sArray[0]);
    }
    return sb.toStriing();
}

- hivejin May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#python

def reverseWords(text):
words = text.split(" ")
reversed_words = reversed(words)
return ' '.join(reversed_words)

- vinamelody May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseWords(text):
    words = text.split(" ")
    reversed_words = reversed(words)
    return ' '.join(reversed_words)

- vinamelody May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The best possible recursive solution which i feel is possible .. I tested the same for 1000000 size string

public static String reverseWords(String value){
		if(value == null || value.length() == 0)
			return "";
		int index = value.indexOf(" ");
		if(index <= 0)
			return value;
		return reverseWords(value.substring(index +1))+" "+value.substring(0,index);
}

- vrajendra.singh.mandloi May 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.* ;
import java.lang.String;

public class ReverseWords{
	public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    ReverseWords obj = new ReverseWords();

    String result = obj.reverseWords(input);

    System.out.println(result);


	}

 String reverseWords(String value){
   
   int strLen = value.length()-1;  // 0 index
   
   char[] myChar = value.toCharArray();

  int i =0;
  int j = strLen;
 //First reverse the complete string
   while(i<=j){
   	char temp = myChar[i];
   	myChar[i] = myChar[j];
   	myChar[j] = temp;
   	i++;
   	j--;
   }

 int base_index =0;
   
    for(i=0;i<=strLen;i++){
      
      if(myChar[i]==' '){
      
        int a = base_index;
        int b = i-1;
        while(a<=b){
        	char temp = myChar[a];
   	        myChar[a] = myChar[b];
        	myChar[b] = temp;
        	a++;
        	b--;
        }
      	base_index = i+1;

      }

      if(i==strLen){ // reached last character of the string

      int a = base_index;
      int b = i;

      while(a<=b){
        	char temp = myChar[a];
   	        myChar[a] = myChar[b];
        	myChar[b] = temp;
        	a++;
        	b--;
        }
      }
 	
 	}//end of for loop

String result = String.valueOf(myChar);

return result;

}


}

- Arun May 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.* ;
import java.lang.String;

public class ReverseWords{
	public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    ReverseWords obj = new ReverseWords();

    String result = obj.reverseWords(input);

    System.out.println(result);


	}

 String reverseWords(String value){
   
   int strLen = value.length()-1;  // 0 index
   
   char[] myChar = value.toCharArray();

  int i =0;
  int j = strLen;
 //First reverse the complete string
   while(i<=j){
   	char temp = myChar[i];
   	myChar[i] = myChar[j];
   	myChar[j] = temp;
   	i++;
   	j--;
   }

 int base_index =0;
   
    for(i=0;i<=strLen;i++){
      
      if(myChar[i]==' '){
      
        int a = base_index;
        int b = i-1;
        while(a<=b){
        	char temp = myChar[a];
   	        myChar[a] = myChar[b];
        	myChar[b] = temp;
        	a++;
        	b--;
        }
      	base_index = i+1;

      }

      if(i==strLen){ // reached last character of the string

      int a = base_index;
      int b = i;

      while(a<=b){
        	char temp = myChar[a];
   	        myChar[a] = myChar[b];
        	myChar[b] = temp;
        	a++;
        	b--;
        }
      }
 	
 	}//end of for loop





   String result = String.valueOf(myChar);

   return result;
  
 }

}

- Arun May 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{

function reverseWords( str ) {
  
  var revString  = ""
  
  var lastIdx = str.lastIndexOf(" ")
  var firstIdx = str.indexOf(" ")
  var end = str.length
  var word = ""
  
  while ( lastIdx >= firstIdx ) {

    word = str.slice( lastIdx+1, end)
    str = str.slice(0, lastIdx)  
    revString = revString+word+" "
    lastIdx = str.lastIndexOf(" ")
  }
  
  revString = revString + str

  return revString
}

}

- TDR May 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript

{

function reverseWords( str ) {
  
  var revString  = ""
  
  var lastIdx = str.lastIndexOf(" ")
  var firstIdx = str.indexOf(" ")
  var end = str.length
  var word = ""
  
  while ( lastIdx >= firstIdx ) {

    word = str.slice( lastIdx+1, end)
    str = str.slice(0, lastIdx)  
    revString = revString+word+" "
    lastIdx = str.lastIndexOf(" ")
  }
  
  revString = revString + str

  return revString
}

}

- TDRBY May 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String str) {
        String[] arr = str.split(" ");
        String tmp;
        int from = 0;
        int to = arr.length - 1;
        while (to > from) {
            tmp = arr[from];
            arr[from++] = arr[to];
            arr[to--] = tmp;
        }
        return String.join(" ", arr);
    }

- andreybavt May 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

(1) Reverse the string
(2) Reverse individual words

- funcoolgeek May 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Space complexity O(1) and Time complexity O(n)

class StringReverse {

	public static void main(String[] argc) {
		StringReverse sr = new StringReverse();
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		String reverseStr = sr.reverseWords(str);
		System.out.println(reverseStr);
	}

	public void reverse(StringBuilder str, int i, int j) {
		while (i < j) {
			char temp = str.charAt(j);
			str.setCharAt(j, str.charAt(i));
			str.setCharAt(i, temp);
			i++;
			j--;
		}

	}

	public String reverseWords(String str) {

		if (str == null || str.length() == 0) {
			return null;
		}

		final char SPACE = ' ';
		int start = 0;
		int curr = 0;
		StringBuilder sb = new StringBuilder(str);

		reverse(sb, 0, sb.length() - 1);

		while (curr < sb.length()) {
			if (sb.charAt(curr) == SPACE) {
				reverse(sb, start, curr-1);
				start = curr + 1;
			}
			curr = curr + 1;
		}

		reverse(sb, start, curr-1);

		return sb.toString();
	}
}

- sandeep1001 May 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static private string ReverseWords(string originalString)
        {
            Stack<string> myStack = new Stack<string>();
            foreach (string subString in originalString.Split(' '))
            {
                myStack.Push(subString);
            }

            string reversedString = "";
            while (myStack.Count > 0)
            {
                reversedString += myStack.Pop();
                if (myStack.Count > 0)
                {
                    reversedString += " ";
                }
            }

            return reversedString;
        }

- Anonymous June 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static private string ReverseWords(string originalString)
        {
            Stack<string> myStack = new Stack<string>();
            foreach (string subString in originalString.Split(' '))
            {
                myStack.Push(subString);
            }

            string reversedString = "";
            while (myStack.Count > 0)
            {
                reversedString += myStack.Pop();
                if (myStack.Count > 0)
                {
                    reversedString += " ";
                }
            }

            return reversedString;

}

- J June 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static private string ReverseWords(string originalString)
        {
            Stack<string> myStack = new Stack<string>();
            foreach (string subString in originalString.Split(' '))
            {
                myStack.Push(subString);
            }

            string reversedString = "";
            while (myStack.Count > 0)
            {
                reversedString += myStack.Pop();
                if (myStack.Count > 0)
                {
                    reversedString += " ";
                }
            }

            return reversedString;
        }

- kahizer241237 June 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseWords(words_str):
	words = words_str.split(" ")
	reversed_words = reversed(words)
	return " ".join(reversed_words)

- summermontreal June 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def word_reverser(str):
    if not str:
        return ''
    str_array = str.split()
    return " ".join(str_array[::-1])

print word_reverser("Man bites dog")
print word_reverser("")
print word_reverser("One")

- Slava June 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x = 'Man bites dog'.split(' ')
y = ''
for i in xrange(len(x)-1, -1, -1):
y += x[i] + ' '
print y

- Indraja.Punna June 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{def reverse_string(string):
    return ' '.join(string.split(' ')[::-1])

}

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

All of these solutions are wrong (too naive).

None of these answers account for sentence punctuation. You should ask this in an interview and reverse the words without reversing punctuation.

- Anon July 09, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Stack;

public class ReverseSentence {
	public static void main(String[] args) {
		String ans = reverseSentence("Man bites dog");
		System.out.println(ans);
	}
	public static String reverseSentence(String s) {
		Stack<String> st = new Stack<String>();
		
		String[] words = s.split(" ");
		for(String w : words) {
			st.push(w);
		}
		StringBuilder sb = new StringBuilder();
		while(!st.empty()) {
			sb.append(st.pop());
			sb.append(" ");
		}
		sb.deleteCharAt(sb.length() -1);
		return sb.toString();
	}
}

- bosung90 August 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

For those of you using split, reverse, etc - doesn't performance count for anything these days?

C++ (could easily be C or any language), assuming the answer needs to reside in a copied buffer, and not re-write the original (to re-write, reverse string, for each word, reverse word):

#include <iostream>
#include <string>

using namespace std;

string reverseWords(const char* str){
    int len = strlen(str);
    // Allocate memory (from stack, for now):
    char* buffer = (char*)alloca((len+1)*sizeof(char));
    buffer[len-1] = '\0'; // null terminate the string
    int end = 0, start = len - 1; // end is the end of the copied buffer, start is the beginning of the word we copy
    // Iterate string from end to start
    for (int i=len-1;i>=0;--i){
        if (str[i] == ' '){ // space?
            // copy the word to the new buffer
            memcpy(buffer + end,str+i+1,start - i);
            // set new start, end
            end+=start-i;
            start = i - 1;
            // add a space and move end of buffer one more notch 
            buffer[end++] = ' ';
        }
    }
    // copy the last word (first word in the original text)
    memcpy(buffer + end, str,start+1);
    return buffer;
}

int main(int argc,char* argv[]){
    cout << reverseWords("Man bytes dog") << endl;
    return 0;
}

- Moshe August 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Another C version

#include <stdio.h>

char STRING[] = {"dog and cat bites man and woman"};


void
reverse(char *str)
{
   char *tStr;
   int count = 0;

   if (*str == '\0')  // end of string; Recursion base case
       return;

   tStr = str; // make copy of pointer to traverse string

   while((*tStr != ' ') && (*tStr != '\0')) {
       // traverse till next word or end of the string
       tStr++;
       count++;
   }   

   tStr++; // Skip pass ' ' [white space]
   reverse(tStr);    // recursion, repeat same process for rest of the string.

   printf("%.*s ", count, str);

#if 0
   // Another way to print string
   int i = 0;
   while (count) {
       printf("%c", str[i++]);
       count--;
   }

   printf("%c", ' ');
#endif
}


int
main() {
    printf("%s\n", STRING);
    reverse(STRING);
    printf("\n");
    return 0;
}

output

dog and cat bites man and woman
woman and man bites cat and dog

- praveenmhapsekar September 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Ruby:

def reverse_str str
  str.split.reverse.join(" ")
end

- fdevillamil September 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

std::string reverseWords(std::string str) {
  if (str.size() < =1) return str;
  std::string rstr="";  // reverse string
  std::string tmpstr=""; // temporary string
  for(auto s : str){
      if(s!=' '){tmp+=s;}
      else{rname=" " +tmp+rname;
      tmp="";}
  }
}

- Sam November 09, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is an Objective-C solution in O(log n) time and O(i) space

-(NSString *)reverseWords:(NSString *)value{
    
    NSString *result;
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[value componentsSeparatedByString:@" "]];
    
    for(int i = 0; i < [tempArray count] / 2; i++){
        
        [tempArray exchangeObjectAtIndex:((int)[tempArray count] - i - 1) withObjectAtIndex:i];
    }
    
    result = [[tempArray valueForKey:@"description"] componentsJoinedByString:@" "];
    
    return result;
}

- oscarsanchez1937 November 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverse(string &s, int i, int j)
{
    int left = i;
    int right = j;
    while(left< right)
    {
        int temp;
        temp = s[left];
        s[left]= s[right];
        s[right] = temp;
        left++;
        right--;
    }
}
int main (int argc, char *ARgv[])
{
    string input = "Tiger eats boy  and      space   leftover#@# ";
    reverse(input, 0,(int)input.size()-1);  //master reverse
    int lindex = 0;
    int rindex = 0;
    while(rindex < (int)input.size())
    {
        
        while(input[rindex]!= ' ' && rindex < input.size())
          rindex++;
        reversestring(input, lindex, rindex-1);
        rindex++;
        while(input[rindex] == ' ' && rindex < input.size())
            rindex++;
        lindex = rindex;
    }
    cout << input << endl;
    
    
    return 0;
}

- Ad December 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
sent = "Man bites dog"

def revstr(s):
lenofs = len(s)
s = s.split()
x = " ".join(reversed(s))
print("Reversed String: %s" % x)

revstr(sent)
}}

- Anonymous September 02, 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