Facebook Interview Question: Given a string, remove all th... | Glassdoor

Interview Question

Software Engineer Interview Palo Alto, CA

Given a string, remove all the duplicate characters (not

  necessarily consecutive)
Tags:
string-processing algorithms
Answer

Interview Answer

9 Answers

5

void removeDuplicates(char *in, char *out) {
    bool seen[NUM_CHARS] = {false};
    while (*p != 0) {
        if (seen[*p] == 0) {
            *out++ = *p;
        }
        seen[*p] = true;
    }
}

Interview Candidate on Apr 24, 2011
1

public class StringRemove {
    private final String baseString = "abcdefghijklmnopqrstuvwxyz12345678910";
    private final List finalMap = new ArrayList();
    private StringBuffer sb = new StringBuffer();

    private void findDup(){
        for(int i=1 ; i <= baseString.length() ; i++) {
            String sLocal = baseString.substring(i-1, i);
            if(finalMap.contains(sLocal)){
                finalMap.remove(sLocal);
            }else{
                finalMap.add(sLocal);
            }
        }
        String s = finalMap.toString();
        s = s.replace('[',' ').replace(']',' ').replace(',', ' ').replace(',', ' ').trim().replaceAll(" ", "");
        System.out.println(s);
    }

    public static void main(String s[]){
        StringRemove sr = new StringRemove();
        sr.findDup();
    }

boogyman on May 12, 2011
0

void RemoveDuplicates(char[] arr, int length)
{
    Map charMap = new Map();
    int currenPosition = 0;
    for (int i=0;i

PrinceBoroujerdi on Oct 8, 2011
0

to the last two - just use a boolean array instead of a map or list like Interview Candidate

dc on Oct 28, 2011
0

public class Duplicates {

    public static String removeDuplicates(String str){
        int[] chars = new int[26];
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < str.length(); i++){
            int val = (int)str.charAt(i)-97;
            if(chars[val]==0){
                chars[val]=1;
                sb.append(str.charAt(i));
            }
        }
        return sb.toString();
    }

    public static void main(String[] args){
        String res = removeDuplicates("faaabook");
        System.out.println(res);
    }
}

jh on Dec 9, 2011
2

each char has ASCII code number, so just XOR all those numbers together, duplicates will eliminate each other.

jarik on May 8, 2012
2

void remove_duplicate(char * str, int len)
{
    bool appeared[NUM_CHARS];
    memset(appeared, 0, sizeof(appeared));
    int i = 0, j=0;
    while(i < n)
    {
        if(!appeared[str[i]])
        {
            str[j] = str[i];
            j ++;
            appeared[str[i]] = true;
        }
        i ++;
    }
    str[j] = '\0';
}

hj on Jul 25, 2012
0

store each characted in hashset and them combine

BS on Aug 28, 2012
0

I mean combine them

BS on Aug 28, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.