Facebook Interview Question for Front-end Software Engineers


Country: India
Interview Type: In-Person




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

var string = "ABCSC";
((string.indexOf("ABC") != -1) ? (string.replace(/ABC/gm,"")) : (-1));

- sethtoda November 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 6 vote

Since the question says "use very simple code and concept(ALGORITHM)", I suppose they don't want any sophisticated like the KMP algorithm to find substring occurrences.

int RemoveSubstring(string& text, const string& sub) {
    size_t pos = text.find(sub);
    if (pos == string::npos)
        return -1;
    text.erase(pos, sub.size());
    return 0;
}

- Miguel Oliveira September 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

#include <iostream>
#include <string>

using namespace std;

int main() 
{
	string a,b;  // I will take both string input from user and check whether b is substing of a or not.
	cin>>a;
	cin>>b;
	int idx = 0;
	idx = a.find(b); // Checking whether b is substring of a.
	if(idx == 0)
	{
		int l = b.length();
		a = a.substr(l);
		cout<<a<<"\n";
	}
	else if(idx > 0)
	{
		int l = b.length();
		string temp="";
		temp = a.substr(0,idx);
		a = a.substr(idx+l);
		cout<<temp<<a<<"\n";
	}
	else
	{
		cout<<"-1\n";
	}
	return 0;
}

- shravan40 September 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is incorrect. Note that for input "ZABCSC" and substring "ABC" the string becomes "ZSC".

- Miguel Oliveira September 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Thanks for pointing out my mistake.
I was missing such case. I edited for my answer considering all possibilities, please have a look.
By the way i have only this code into my previous code

else if(idx > 0)
	{
		int l = b.length();
		string temp="";
		temp = a.substr(0,idx);
		a = a.substr(idx+l);
		cout<<temp<<a<<"\n";
	}

- shravan40 September 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

i suggest you don't use "l" as a variable name. it's quite easy to read it as "1" (i did at first there). That should work. I prefer using erase() as described in my answer because the code is simpler.

- Miguel Oliveira September 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Maybe you should use hashing and Rabin-Karp Algo?

- gstepanov@griddynamics.com September 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

JavaScript

(function(){ alert(checkString("ABCSC")); })();

function checkString(s){

  return /ABC/.test(s) ? s.replace(/ABC/g,"SC") : -1

}

- ic3b3rg November 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Almost right... Question is to just return SC back. So change above code

return /ABC/.test(s) ? s.replace(/ABC/g,"") : -1;

- Vishal Singh May 06, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Examples: "zabcaabcbcs" should result "zs" , if there is multiple existence of substring.
can be done very simply in java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class removeSubStr {
	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuffer sf = new StringBuffer();
		System.out.println("Enter main String:");
		sf.append(br.readLine());
		System.out.println("Enter substring to search:");
		String subStr = br.readLine();
		if(removeSubString(sf,subStr) == -1)
			System.out.println("Substr not found");
		else
			System.out.println("replaced string is: " + sf.toString());
	}

	static int removeSubString(StringBuffer mainStr, String subStr)
	{
		String strCopy = mainStr.toString();
		while(mainStr.indexOf(subStr) >= 0)
		{		
			mainStr.delete(mainStr.indexOf(subStr),mainStr.indexOf(subStr)+ subStr.length());
			System.out.println(mainStr.toString());  //intermediate results
		}
		if(strCopy.equals(mainStr.toString()))
			return -1;
		else
			return 0;
	}
}

- pooja basia September 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Well here is a code written very easily in Python 3.3.2, have a look :)

def string():
    a=input("Enter the string: ")
    b=input("Enter the substring: ")
    print("The strings are :",a,b)
    if b in a:
        print("After removing the substring: ",a.replace(b,''))
    else:
        return -1

- SmashDUNK September 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I guess the point is to use logic instead of built in methods.

- Jash Sayani October 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

for 'ABABCCSC' what do you think ans should be 'ABCSC' OR 'SC' ??

- PKT October 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

KMP to find the target in the source string. Then do the following:

void Compact(char *s, int begin, int end, int len) //begin and end are the starting and the ending indices of the target in the source.
for(i=end+1;i<n;begin++,i++)
  s[begin]=s[i];
for(;begin<n;begin++)
  s[begin]=(char)0;

- Anonymous October 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string ABC(string str) {
             string temp="";
             string res = "";
             int j;
             for (int i = 0; i < str.Length; i++) {

                 //j = str.Length - i;
                 for (j=str.Length - i; j > 0; j--)

                     if (str.Substring(i, j) == "ABC")
                     {
                         res = str.Replace("ABC", "");
                         return res;
                     }
                     else
                         res = "-1";
             
             }

             return res;

         }

- Prince November 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

<?php

function search($string, $keyword)
{
    for($i = 0;$i<strlen($string);$i++)
    {
        for($j = 0;$j<strlen($keyword);$j++)
        {
            if($tmp===$keyword) break;
            if(substr($string,$i,1) === substr($keyword,$j,1))
            {
                $tmp = $tmp.substr($string,$i,1);
                $string = substr_replace($string,"",$i,1);
            }
        }
    }
    if(empty($tmp)||trim($tmp)!=trim($keyword)){
        return -1;
    } else {
       return $string;
    }
}

//Main
echo"String-> ";
$string = trim(fgets(STDIN));
echo"Keyword-> ";
$keyword = trim(fgets(STDIN));
echo "Result-> ".search($string,$keyword)."\n";

- yorgen December 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Main {

public static void main(String[] args) {

String string = "ABCSC";
String substring = "ABC";

System.out.println(containsSubString(string, substring));
}

public static String containsSubString(String string, String substring){
if (string.contains(substring)){
int leftIndex = string.indexOf(substring);
int rightIndex = leftIndex + substring.length();
StringBuilder stringBuilder = new StringBuilder(string);
stringBuilder.replace(leftIndex, rightIndex, "");
return stringBuilder.toString();
}
return Integer.toString(-1);
}

}

- Christian Roman December 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Dynamic prorgamming for Longest Common Substring where the substring found needs to be of the length of the needle. And if there could be recursively embedded abcs, then we would probably have to run this continually until the function eventually returns -1.

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

<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
var str="ABCSC";
reg=/ABC/;

if(reg.exec(str))
str=str.replace("ABC", "");
else
return -1;
document.write(str);
</script>
</head>
<body>
</body>
</html>

- Sha He February 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

reg.exec will result an array, since we are not using it, we can just use match/test which just returns boolean

- Shanmugapriya May 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

// with help of RegExp
function check(str, pattern) {
  'use strict';

  var reg = new RegExp(pattern, 'g');
  if (reg.test(str) === false) {
    return -1;
  } else {
    var l = pattern.length;
    var i = str.indexOf(pattern);
    return str.slice(0, i) + str.slice(i + l);
  }

}

// without using RegExp
function vanillaCheck(str, pattern) {
  'use strict';

  var i = 0;
  var l = str.length;
  var result = -1;
  while (i <= l - pattern.length) {
    var s = str.slice(i, i + pattern.length);
    if (s === pattern) {
      result = str.slice(0, i) + str.slice(i + s.length);
      break;
    }
    ++i;
  }

  return result;
}

var s = 'ABCSC';
console.log(check(s, 'BC'));
console.log(vanillaCheck(s, 'BC'));

- Hang October 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

javascript
function check(str, pattern) {
  'use strict'
  var idx = str.indexOf(pattern)
  if (-1 === idx) return idx
  return str.split(pattern).join('')
}

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

function check(str, pattern) {
  'use strict'
  var idx = str.indexOf(pattern)
  if (-1 === idx) return idx
  return str.split(pattern).join('')
}

- Camoni Bala October 26, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
class SubString
{
	public static void main(String args[])
	{
		Scanner src = new Scanner(System.in);
		while(src.hasNextLine())
		{
			String str = src.nextLine();
			String sub = src.nextLine();
			if(str.contains(sub))
			{
				str = str.replace(sub,"");
				System.out.println(str);
			}
			else if(!str.contains(sub))
			{
				System.out.println("-1");
			}
		}
	}
}

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

This was asked on-site? You gotta be kidding. Could you solve it in 45 minutes? :)

- Safi November 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

call remove function recursively removing the subtext. not the best solution, but easy to understand.

public static void main(String args[])
{
String s = "ABCSC";
String r = "ABC";
System.out.println(remove(s, r));
}

public static String remove(String s, String r)
{
if(s.indexOf(r) == -1) //removed all
return s;

int index = s.indexOf(r);
String processed = s.substring(0, index)
+ s.substring(index+r.length(), s.length());

return remove(processed, r);
}

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

Not the best solution, but easy to understand.

public static void main(String args[])
	{
		String s = "ABCSC";
		String r = "ABC";
		System.out.println(remove(s, r));
	}
	
	public static String remove(String s, String r)
	{
		if(s.indexOf(r) == -1) //removed all
			return s;
		
		int index = s.indexOf(r);
		String processed = s.substring(0, index) 
				+ s.substring(index+r.length(), s.length());
		
		return remove(processed, r);
	}

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

I don't remember if this the KMP algorithm but I think is similarly good as it is O(n) solution worst case would be O(n^2) if there are always hash-code collisions.

public static bool SubStringExist(string S, string subStr)
{
	long hahs = 0;
	foreach(char c in subStr)
		hash += c.GetHashCode();

	// Not needed but using for ease of understanding
	int head = 0;
	int tail = 0;

	long sHash = 0;
	for(; tail < S.Length; tail++)
		sHash += S[tail].GetHashCode();

	for(; tail < S.Length; tail++)
	{
		if(hash == strHash)
		{
			// Verify in case of hash collisions
			bool equal = true;
			for(int j = head; j < tail; j++)
			{
				if(S[j] != subStr[j-head])
				{
					equal = false;
					break;
				}
			}

			if(equal) 
			{
				return true;
			}
		}

		sHash += S[tail].GetHashCode() - S[head].GetHashCode();
		head++;
	}
	

}

- Nelson Perez March 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Very simple problem. This is the JavaScript solution, whose worst case performance is o(n).

<script>
function isSubString(sourceStr, subStr, sourceIndex, subStrIndex) {
	
	if (sourceIndex >= sourceStr.length) {
		return -1;		
	}
	
	if (subStrIndex >= subStr.length) {
		var res = sourceStr.substr(0, sourceIndex - (subStr.length - 1));
		
		if (sourceIndex < sourceStr.length - 1) { 
			res += sourceStr.substr(sourceIndex + 1);
		}
		
		return res;
	}

	++ sourceIndex;
			
	if (sourceStr.charAt(sourceIndex) == subStr.charAt(subStrIndex)) {
		++subStrIndex;
		return isSubString(sourceStr, subStr, sourceIndex, subStrIndex);
	} else {
		return isSubString(sourceStr, subStr, sourceIndex, 0);
	}
}

alert(isSubString("xabc", "abc", 0, 0)); //x
alert(isSubString("ababbabcd", "abc", 0, 0)); //ababbd
alert(isSubString("ababbabcd", "abd", 0, 0)); //-1
alert(isSubString("ababbabcd", "bcd", 0, 0)); //ababba
alert(isSubString("ababbabcd", "ccd",0, 0)); //-1
alert(isSubString("ababbabcd", "bba", 0, 0)); //ababcd
</script>

- Good Maker August 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SubStringFind {

	public static String findStr(String mainString, String subString) {

		if (mainString.contains(subString)) {
			return mainString.replace(subString, "");

		} else {
			return "-1";
		}

	}

	public static void main(String[] args) {

		String result = SubStringFind.findStr("ABCSC", "ABC");

		System.out.println(result);

	}

}

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

var remove  = function(Str, subStr){
        if(Str.indexOf(subStr) === -1){
            return -1;
        }
        return Str.replace(subStr,"");
    };

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

Javascript code:

function removeSub(str, sub) {
    return str.indexOf(sub) != -1 ? str.replace(sub, "") : -1;
}

- Raul Rivero March 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string str = "ABCSC";
string result = string.Empty;

if (str.Contains("ABC"))
{
result = str.Replace("ABC", "");
}

Console.WriteLine(result);

- vou xiong April 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string str = "ABCSC";
            string result = string.Empty;

            if (str.Contains("ABC"))
            {
                result = str.Replace("ABC", "");
            }

            Console.WriteLine(result);

- vou xiong April 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function checkStr(str, subStr) {
  var index = str.indexOf(subStr);
  if (index === -1) return index;
  return str.replace(subStr, '');
}

- andrew.m.henderson September 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

console.log(findSubstring('TRABCSC', 'ABC'));

function findSubstring(text, substring) {
  let index=0;

  for(let i=0;i<text.length;i++){
      if (substring[index]==text[i]) {
            if(index == substring.length-1) 
            {
              return trimString(text, i-substring.length+1, substring.length);
            }
            index++;
      }else{
        index = 0;
      }
  }
  return -1;
}

function trimString(text, start, length){
    let s='';
    for(let i=0;i<start;i++){
      s+= text[i];
    }
    for(let i=start+length;i<text.length;i++){
      s+= text[i];
    }
  return s;
}

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

let str = 'ABCSC';
const reg = /(ABC)/gm;

let checkStr = str => str.match(reg) ? str.replace(reg, '') : -1;

- Michael Tempest January 27, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

This is fairly simple in javascript using the .contains and .replace String methods.

var text = 'ABCSC',
    subtext = 'ABC';

text.contains(subtext) ? text.replace(subtext, '') : -1;

- whiteorb October 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

String do not have that method

- qbaty.qi February 11, 2014 | Flag


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