Salesforce Interview Question for Quality Assurance Engineers


Country: United States
Interview Type: Phone Interview




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

public static void main(String[] args) {
String s1 = "Salesforce is the best company to work for";
char[] chars = s1.toLowerCase().toCharArray();
int count;
for (int i = 0; i < chars.length; i++) {
count = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
count++;
break;
}
}
if (count == 0) {
System.out.println(chars[i]);
break;
}
}
}

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

asymptotically not optimal solution.
In case of all distinct characters this is O(n^2) solution.
Using hashtable allows to create O(n) solution.

- zr.roman January 28, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Outout is not number 1, it is first non repeating letter "l" (Letter "L" lower case)

- eminsqa January 28, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

# -*- coding: utf-8 -*-

testString = "Salesforce is the best company to work for"


def firstNoRepeated(str):
str = " " + str.lower() + " "
for l in str:
i = str.index(l)
if (l not in str[:i-1]) and (l not in str[i+1:]):
return l
break

print firstNoRepeated(testString)

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

public class careercup {
public static void main(String[] args) {
String s1 = "Salesforce is the best company to work for";
char[] chars = s1.toLowerCase().toCharArray();
int count;
for (int i = 0; i < chars.length; i++) {
count = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
count++;
break;
}
}
if (count == 0) {
System.out.println(chars[i]);
break;
}
}
}
}

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

public void minCharCounter(String word) {
LinkedHashMap<Character, Integer> charcount = new LinkedHashMap<>();
for (int i = 0; i < word.length(); i++) {
if (charcount.get(word.charAt(i)) == null) {
charcount.put(word.charAt(i), 1);
} else {
charcount.put(word.charAt(i), charcount.get(word.charAt(i)) + 1);
} }

int min = Integer.MAX_VALUE; char min_char = (char) 256;
for (Map.Entry<Character, Integer> count : charcount.entrySet()) {
if(count.getValue() < min) {
min = count.getValue();
min_char = count.getKey();
} }

System.out.println(min_char + ":" + min);
}

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

public void minCharCounter(String word) {
word = word.toLowerCase();
LinkedHashMap<Character, Integer> charcount = new LinkedHashMap<>();
for (int i = 0; i < word.length(); i++) {
if (charcount.get(word.charAt(i)) == null) {
charcount.put(word.charAt(i), 1);
} else {
charcount.put(word.charAt(i), charcount.get(word.charAt(i)) + 1);
}
}

int min = Integer.MAX_VALUE; char min_char = (char) 256;
for (Map.Entry<Character, Integer> count : charcount.entrySet()) {
if(count.getValue() < min) {
min = count.getValue();
min_char = count.getKey();
}
}
System.out.println(min_char + ":" + min);
}

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

using hashtable do 1st scan and store chars and their frequencies to that hashtable.
Then do 2nd scan and compare each char's frequency to 0. When you hit 0 for the first time - break and return the corresponding char.

- zr.roman January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

First character with 0 frequency may not be the first non repeated element.
We can store the index as part of the key generated or as value while forming the hash table and check during second scan for lower index ,0 frequency char.

- Sv January 30, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

in my algorithm first character with 0 frequency will be the first non repeated element, because both scans are done against the input string.

- zr.roman February 06, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes your algorithm is..correct...
I thought second scan is done against hashtable...

- Sv February 10, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

The following solution will be more optimal as you do not have nested loops. The question should also dictate whether you can use the java api or solve the problem using primitive arrays.

public static String findFirstNonRepeatingChar(String string) {
		
		//ascii mapping of char a.  Given ascii values are incremental from A-Z we can just subtract ascii value of A
		//to give us the count mapping of the char in the array
		int ASCII_VALUE_A=97;
		
		
		int[] charCounts = new int[26]; //0==a, 1==b, 2==c ...
		char[] charSequence = new char[26]; //the order in which the chars appeared in the supplied string
		int charSequenceCount=0;
		
		for(char character : string.toLowerCase().toCharArray()) {
			if(character != ' ') {
				
				//Have we seen this char before?
				int countIndex = ((int)character)-ASCII_VALUE_A;
				int count = charCounts[countIndex];
				
				if(count == 0) //new char not seen before so store in the char sequence in the next free slot
				  charSequence[charSequenceCount++] = character;
				
				//increment the number of occurrences count for the given char
			    charCounts[countIndex]=++count;
			}
		}
		
		//iterate over the chars in the order they appeared in the supplied string and find the first occurrence where count == 1
		for(int i=0; i<charSequenceCount; i++) {
			char c = charSequence[i];
				
			if(charCounts[((int)c)-ASCII_VALUE_A]==1) {
				return c+"";
			}
		}
		
		return "No unique characters in sentence : " + string;
	}

- Justin Flanagan January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The following solution avoids the worst case O(n2) by removing the nested loop. Does not use the java api either. Question, ideally would state whether it needs to be solved using raw code or using Java API.

public static String findFirstNonRepeatingChar(String string) {
		
		//ascii mapping of char a.  
		int ASCII_VALUE_A=97;
		
		 //0==a, 1==b, 2==c ...
		int[] charCounts = new int[26];
		
		//the order in which the chars appeared in the supplied string
		char[] charSequence = new char[26]; 
		
		int charSequenceCount=0;
		
		for(char character : string.toLowerCase().toCharArray()) {
			if(character != ' ') {
				
				//Have we seen this char before?
				int countIndex = ((int)character)-ASCII_VALUE_A;
				int count = charCounts[countIndex];
				
				//new char not seen before so store in the char sequence
				if(count == 0)
				  charSequence[charSequenceCount++] = character;
				
				//increment the number of occurrences count for the given char
			    charCounts[countIndex]=++count;
			}
		}
		
		//iterate over the chars in the order they appeared in the supplied string
		for(int i=0; i<charSequenceCount; i++) {
			char c = charSequence[i];
				
			if(charCounts[((int)c)-ASCII_VALUE_A]==1) {
				return c+"";
			}
		}
		
		return "No unique characters in sentence : " + string;
	}

- justinmflanagan72@googlemail.com January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Apologies, it does the api for the toLowerCase() call.

- justinmflanagan72@googlemail.com January 28, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.learning;

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
find();
}

public static String find() {

String searchIn = "This is the ue";
char[] searchInArray = searchIn.toLowerCase().toCharArray();
String notRepeated = "notFound";
int counter = 0;
for (char c : searchInArray) {
for (char d : searchInArray) {
if (c == d) {
counter = counter + 1;
}
if (counter > 1) {
break;
}
}
if (counter == 1) {
System.out.println(String.valueOf(c));
return String.valueOf(c);
}
counter =0;
}
return null;

}

}

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

package com.learning;

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
find();
}

public static String find() {

String searchIn = "This is the ue";
char[] searchInArray = searchIn.toLowerCase().toCharArray();
String notRepeated = "notFound";
int counter = 0;
for (char c : searchInArray) {
for (char d : searchInArray) {
if (c == d) {
counter = counter + 1;
}
if (counter > 1) {
break;
}
}
if (counter == 1) {
System.out.println(String.valueOf(c));
return String.valueOf(c);
}
counter =0;
}
return null;

}

}

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

package com.learning;

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
find();
}

public static String find() {

String searchIn = "This is the ue";
char[] searchInArray = searchIn.toLowerCase().toCharArray();
String notRepeated = "notFound";
int counter = 0;
for (char c : searchInArray) {
for (char d : searchInArray) {
if (c == d) {
counter = counter + 1;
}
if (counter > 1) {
break;
}
}
if (counter == 1) {
System.out.println(String.valueOf(c));
return String.valueOf(c);
}
counter =0;
}
return null;

}

}

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

{{
string = "Salesforce is the best company to work for"
string = string.lower()
list(string)

counter = 0

for x in string:
if not x in string[counter+1:]:
print(x)
break
else:
counter += 1

}}

- Enrique Ramon January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Scala solution:

def main(strings: Array[String]) = {
    val s = "Salesforce is the best company to work for"

    val map = mutable.Map[Char, Int]()
    s.toCharArray.zipWithIndex.foreach{
      case (c, i) =>
        val lower = c.toLower
        map.update(lower, map.getOrElse(lower, 0) + 1)
    }

    println(s.toCharArray.find(c => map(c.toLower) == 1))
  }

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

Scala solution:

def main(strings: Array[String]) = {
    val s = "Salesforce is the best company to work for"

    val map = mutable.Map[Char, Int]()
    s.toCharArray.zipWithIndex.foreach{
      case (c, i) =>
        val lower = c.toLower
        map.update(lower, map.getOrElse(lower, 0) + 1)
    }

    println(s.toCharArray.find(c => map(c.toLower) == 1))
  }

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

public class FirstNonRepeatedCharacter {

public static void main(String[] args) {
String str = "shhrravvannsk";
str = str.toLowerCase();

String nonRepeatedString = firstNonRepeatedCharacter(str, 0);
System.out.println(nonRepeatedString);
}

public static String firstNonRepeatedCharacter(String fullString, int characterIndex) {
if (fullString == null || characterIndex < 0 || characterIndex > fullString.length() - 1) {
return null;
}

String subStringToCheck = fullString.substring(0, characterIndex) + fullString.substring(characterIndex + 1, fullString.length());

if (!subStringToCheck.contains(fullString.charAt(characterIndex)+"")) {
return fullString.charAt(characterIndex)+"";
}

return firstNonRepeatedCharacter(fullString, ++characterIndex);
}

}

- Shravan Kumar Sabavat January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeatedCharacter {
	
	public static void main(String[] args) {
		String str = "shhrravvannsk";
		str = str.toLowerCase();

		String nonRepeatedString = firstNonRepeatedCharacter(str, 0);
		System.out.println(nonRepeatedString);
	}
	
	public static String firstNonRepeatedCharacter(String fullString, int characterIndex) {
		if (fullString == null || characterIndex < 0 || characterIndex > fullString.length() - 1) {
			return null;
		}
		
		String subStringToCheck = fullString.substring(0, characterIndex) + fullString.substring(characterIndex + 1, fullString.length());
		
		if (!subStringToCheck.contains(fullString.charAt(characterIndex)+"")) {
			return fullString.charAt(characterIndex)+"";
		}
		
		return firstNonRepeatedCharacter(fullString, ++characterIndex);
	}

}

- Shravan Kumar Sabavat January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeatedCharacter {
	
	public static void main(String[] args) {
		String str = "Salesforce is the best company to work for";
		str = str.toLowerCase();

		String nonRepeatedString = firstNonRepeatedCharacter(str, 0);
		System.out.println(nonRepeatedString);
	}
	
	public static String firstNonRepeatedCharacter(String fullString, int characterIndex) {
		if (fullString == null || characterIndex < 0 || characterIndex > fullString.length() - 1) {
			return null;
		}
		
		String subStringToCheck = fullString.substring(0, characterIndex) + fullString.substring(characterIndex + 1, fullString.length());
		
		if (!subStringToCheck.contains(fullString.charAt(characterIndex)+"")) {
			return fullString.charAt(characterIndex)+"";
		}
		
		return firstNonRepeatedCharacter(fullString, ++characterIndex);
	}

}

- shravan.naik1988 January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My friend gave 3 solutions here: capacode. com/string/find-first-unique-character/

It's more interesting if we can solve the problem with just ONE scan on the string.

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

An answer that uses LinkedHashMap (to maintain insertion order). Overall O(n) time

public static Character firstNonRepeating(String s)
	{
		if(s == null || s.isEmpty()) { throw new IllegalArgumentException();}
		if(s.length() == 1) { return s.charAt(0);}
		//strip white space
		s = s.replace(" ", "");
		s = s.toLowerCase();
		char[] split = s.toCharArray();
		LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

		for(char c : split)
		{
			if(map.containsKey(c))
				map.put(c, map.get(c) + 1);
			else
				map.put(c, 1);
		}

		for(Entry<Character,Integer> entry : map.entrySet())
		{
			if(entry.getValue()==1)
				return entry.getKey();
		}
		
		return null;
		
	}

- fayezelfar January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I have a question.
Why do I get l with your solution?
Should we get i?
I thought the question is first non-repeatable character for a non-repeatable word in the string. Is it the first non-repeatable character? And, that is why your solution return l. However, the example is shown I as a solution.

Thank you for posting the solution.

- Why do I get answer l with your solution? May 26, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Never mind. The answer is l. I realize the information I overlook.
Thanks for a great answer.

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

Ruby solution.

a = "Salesforce is the best company to work for"

hash = Hash.new(0)

a.downcase.split("").each do |letter|
    hash["#{letter}"] += 1
end

hash.index(1)

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

a = "Salesforce is the best company to work for"

hash = Hash.new(0)

a.downcase.split("").each do |letter|
    hash["#{letter}"] += 1
end

hash.index(1)

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

a = "Salesforce is the best company to work for"

hash = Hash.new(0)

a.downcase.split("").each do |letter|
    hash["#{letter}"] += 1
end

hash.index(1)

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

O(n), PHP language

function L($str, $position = 1){
	$a = str_split(strtolower(str_replace(' ', '', $str)));
	for($i = 0, $b = array(); $i < sizeof($a); $i++){
		if(!isset($b[$a[$i]])){
			$b[$a[$i]] = 0;
		}
		$b[$a[$i]]++;
	}
	return array_search($position, $b);
}

echo L('Salesforce is the best company to work for');

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

Python

s = 'Salesforce is the best company to work for'
next(x for x in s if len([y for y in s if y == x.lower()]) == 1)

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

loop through the string from back
make an array a[26], where a[0]= count of 'a' and a[25]=count of 'z'
make a temp(find) char variable
if the char is in a[], increment count
if the char is not in a[](a[i]==0), increment count, put it into find
after the end of loop, the value of find is the 1st non-repeated char

- mohapatrasandeep60 January 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char findNonRepeated(string str)
{
     int count[27]={0,0,0,0,0,0,0,0,0,0,0....27 times};
     char find;
     int temp;
     for(string::reverse_iterator i=str.rbegin();i!=str.rend(),i++)
     {
         temp = *i-'a';
         if (!(temp>=0 && temp<=25 ))
         {
             temp = *i-'A';
             if (!(temp>=0 && temp<=25 ))
             temp=26;//blanc space
         }
        .if(a[temp]++==0)
             find= *it;
      
     }
    return find;
}

- mohapatrasandeep60 January 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Initialize an array A[26] with value -1
input_string = input_string.toupper()
for (i=0; i<len(input_string); i++) {
ch = input_string[i] - 'A'
if (A[ch] == -1) {
A[ch] = i
} else if (A[ch] > -1) {
A[ch] = -2;
}
}

min = 1000000
index = -1
for (i=0; i<26; i++) {
if (A[i] >= 0 and A[i] < min) {
min = A[i]
index = i
}
}

print ch(index)+65

- johnes.jk February 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

s1 = "Salesforce is the best company to work for"
def findFirstNonRepeated(s1):
char_freq = dict()
ranking = {}
for idx,i in enumerate(s1.lower()):
char_freq[i] = char_freq.get(i,0)+1
ranking[i]=idx

#get all non repeating char
score=[ (ranking[k],k) for (k,v) in char_freq.items() if v==1]
print "First non repeating: ", sorted(score,reverse=True)[-1]

First non repeating: (2, 'l')

- Andre.S February 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python solution
{{
s1 = "Salesforce is the best company to work for"
def findFirstNonRepeated(s1):
char_freq = dict()
ranking = {}
for idx,i in enumerate(s1.lower()):
char_freq[i] = char_freq.get(i,0)+1
ranking[i]=idx

#get all non repeating char
score=[ (ranking[k],k) for (k,v) in char_freq.items() if v==1]
print "First non repeating: ", sorted(score,reverse=True)[-1]


First non repeating: (2, 'l')
}}

- Andre.S February 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python

s1 = "Salesforce is the best company to work for"
def findFirstNonRepeated(s1):
    char_freq = dict()
    ranking = {}
    for idx,i in enumerate(s1.lower()):
         char_freq[i] = char_freq.get(i,0)+1
         ranking[i]=idx
    
    #get all non repeating char
    score=[ (ranking[k],k) for (k,v) in char_freq.items() if v==1]
    print "First non repeating: ", sorted(score,reverse=True)[-1]

First non repeating: (2, 'l')

- Andre.S February 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static char firstNonRepeatedChar(String str) {
        // A good question to ask is what Space is the first non repeated char. Do we consider 
        // it or not.

        if (str.length() == 0 || str == null) {
            return ' '; // Depending what interviewer want in this case.
        }

        // Depending on whether interviewer want take in account UniCode. I am not considering it
        // and I am just using 256 ASCII char
        int[] charArr = new int[256];

        // Question for Interviewer whether we are treating lower and upper case same or not. I am
        // treating it same.
        String str1 = str.toLowerCase();
        for (int i = 0; i < str1.length(); i++) {
            int val = (int) str1.charAt(i);
            charArr[val]++;
        }

        for (int i = 0; i < str1.length(); i++) {
            int val = (int) str1.charAt(i);
            if (charArr[val] == 1) {
                return str1.charAt(i);
            }
        }

        return ' ';
    }

- Scorpion King February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
	char ceo[50];
	int i,j,c,l;
	gets(ceo);
	l=strlen(ceo);
	for(i=0;i<l;i++)
	{
		c=0;
		for(j=0;j<l;j++)
		{
			if(j!=i)
			{
				if(ceo[i]==ceo[j])
				{
					c++;
				}
			}
		}
		if(c==0)
			break;
	}
	if(c==0)
		printf("%c",ceo[i]);
	else
		printf("All letters in the string are repeated");
	getch();
}

- saai beginner February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void firstSingleChar(String word) {
		word = word.toLowerCase();
		char c[] = word.toCharArray();
		for (int i = 0; i < c.length; i++) {
			System.out.println(word.lastIndexOf(c[i]) + ":" + word.indexOf(c[i]));
			if (word.lastIndexOf(c[i]) == word.indexOf(c[i])) {
				System.out.println(c[i]);
				break;
			}
		}
	}

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

public void firstSingleChar(String word) {
	word = word.toLowerCase();
	char c[] = word.toCharArray();
	for (int i = 0; i < c.length; i++) {
		System.out.println(word.lastIndexOf(c[i]) + ":" + word.indexOf(c[i]));
		if (word.lastIndexOf(c[i]) == word.indexOf(c[i])) {
			System.out.println(c[i]);
			break;
		}
	}
}

- Cezar February 06, 2016 | 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 s = "Salesforce is the best company to work for";
s = s.toLowerCase();
int ht[] = new int[127];
LinkedList<Character> list = new LinkedList<Character>();
for (int i=0; i < s.length(); i++) {
final char ch = s.charAt(i);
list.add(i, ch);
if (ht[ch] != -1) {
ht[ch]++;
if (ht[ch] > 1) {
ht[ch] = -1;
}
}
}
for (Character c : list) {
if (ht[c.charValue()] != -1 && ht[c.charValue()] == 1) {
System.out.println("First non-repeat character: " + c);
break;
}
}
}

/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}

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

public static char firstNonRepeatedChar(String s){
char c=Character.MIN_VALUE;

for(int i=0;i<s.length();i++){
for(int j=1;j<s.length()-1;j++){
if(s.charAt(i)==s.charAt(j)){
j--;
c=s.charAt(j);
break;
}
}

}

return c;
}

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

public static char firstNonRepeatedChar(String s){
		char c=Character.MIN_VALUE;

		for(int i=0;i<s.length();i++){
			for(int j=1;j<s.length()-1;j++){
				if(s.charAt(i)==s.charAt(j)){
					j--;
					c=s.charAt(j);
					break;
				}
			}
			
		}
		
		return c;
	}

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

String findFirstNonRepeatChar(String input) {
if(input == null || input.length() ==0)
return "";
char[] inputA = input.toLowerCase().toCharArray();
Map<Character, Integer> map = new HashMap<>();
for(char ch : inputA) {
if(!map.containsKey(ch))
map.put(ch, 1);
else
map.put(ch, map.get(ch) + 1);
}
for(char ch : inputA) {
if(map.get(ch) == 1) {
return String.valueOf(ch);
}
}
return "";
}

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

public class FirstNonRepeatedChar {
    static int[] a = new int[127];

    public static char find(String string) {
        String s = string.toLowerCase();
        for (char c : s.toCharArray()) {
            a[c]++;
        }
        for (char c : s.toCharArray()) {
            if (a[c] == 1) return c;
        }
        return '\00';
    }

}

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

class MyOwnException extends Exception {
    public MyOwnException(String str) {
        super(str);
    }
}

class NonRepeatavieChar {

    public static char getNonRepeatativeChar(String str1) throws MyOwnException {
        if (str1.length() == 0 || str1 == null) {
            throw new MyOwnException("Given String is not valid");
        }

        int[] chArr = new int[26];
        String str = str1.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            int temp = str.charAt(i) - 'a';
            if (temp >= 0 && temp < 26) {
                chArr[temp]++;
            }
        }

        for (int i = 0; i < str.length(); i++) {
            int temp = str.charAt(i) - 'a';
            if (temp >= 0 && temp < 26) {
                if (chArr[temp] == 1) {
                    return str.charAt(i);
                }
            }
        }
        return '\0';
    }
}

public class FirstNonRepeatativeChar {

    public static void main(String[] args) throws MyOwnException {
        System.out.println(NonRepeatavieChar
                .getNonRepeatativeChar("Salesforce is the best company to work for"));
    }
}

- Scorpion King March 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

One liner solution.

public char firstNonRepeatingCharacter(String s){

 	int i =0;

	for(char c : s.toCharArray()){
		
		if(s.indexOf(c,++i) < 0 ){
			return c;
		}
	}
}

- rohitpratapitm April 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class nonRepeated {

    private Map<Character, Boolean> charMap;
    private Set<Character> dupeSet;
    private Set<Character> nonDupeSet;
    private char[] cArray;
    private String s;

    public nonRepeated() {
        dupeSet = new LinkedHashSet<>();
        nonDupeSet = new LinkedHashSet<>();
        charMap = new LinkedHashMap<>();
    }

    public Integer arraySol(String input){
        int[] arr = new int[26];
        int index = 0;
        cArray = input.toLowerCase().toCharArray();

        for(char c: cArray){
            index = c-'a';
            arr[index]  = ++arr[index];
        }

        for(int i: arr){
            if(i == 1)
                return i;
        }
        return null;
    }

    private Character getFirstEntry() {
        Iterator it = charMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            if (!(boolean) pair.getValue()) {
                return (char) pair.getKey();
            }
            it.remove(); // avoids a ConcurrentModificationException
        }
        return null;
    }

    public char firstChar(String input) {
        cArray = input.toLowerCase().toCharArray();

        for (char c : cArray) {
            if (!charMap.containsKey(c)) {
                charMap.put(c, false);
            } else {
                charMap.put(c, true);
            }
        }

        return getFirstEntry();
    }

    public static void main(String[] args){
        nonRepeated nR = new nonRepeated();
        System.out.println("First non repeated character: " +nR.firstChar("GeeksForGeeks"));
        System.out.println("First non repeated index: " +nR.arraySol("GeeksForGeeks"));
    }

- Siddharth More April 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class nonRepeated {

private Map<Character, Boolean> charMap;
private Set<Character> dupeSet;
private Set<Character> nonDupeSet;
private char[] cArray;
private String s;

public nonRepeated() {
dupeSet = new LinkedHashSet<>();
nonDupeSet = new LinkedHashSet<>();
charMap = new LinkedHashMap<>();
}

public Integer arraySol(String input){
int[] arr = new int[26];
int index = 0;
cArray = input.toLowerCase().toCharArray();

for(char c: cArray){
index = c-'a';
arr[index] = ++arr[index];
}

for(int i: arr){
if(i == 1)
return i;
}
return null;
}

private Character getFirstEntry() {
Iterator it = charMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (!(boolean) pair.getValue()) {
return (char) pair.getKey();
}
it.remove(); // avoids a ConcurrentModificationException
}
return null;
}

public char firstChar(String input) {
cArray = input.toLowerCase().toCharArray();

for (char c : cArray) {
if (!charMap.containsKey(c)) {
charMap.put(c, false);
} else {
charMap.put(c, true);
}
}

return getFirstEntry();
}

public static void main(String[] args){
nonRepeated nR = new nonRepeated();
System.out.println("First non repeated character: " +nR.firstChar("GeeksForGeeks"));
System.out.println("First non repeated index: " +nR.arraySol("GeeksForGeeks"));
}

- Siddharth More April 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def repeated(word):
s = list(word.lower())
dct={}
position=[]
length=len(s)
for i in range(int(length)):
if dct.has_key(s[i]):
dct[s[i]] +=1
else:
dct[s[i]]=1
print dct

for i in dct:
if dct[i] == 1:
position.append(s.index(i))

position.sort()
print position
return s[position[0]]



print repeated("Salesforce is the best company")

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

def repeated(word):
s = list(word.lower())
dct={}
position=[]
length=len(s)
for i in range(int(length)):
if dct.has_key(s[i]):
dct[s[i]] +=1
else:
dct[s[i]]=1
print dct

for i in dct:
if dct[i] == 1:
position.append(s.index(i))

position.sort()
print position
return s[position[0]]



print repeated("Salesforce is the best company")

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

def repeated(word):
    s = list(word.lower())
    dct={}
    position=[]
    length=len(s)
    for i in range(int(length)):
        if dct.has_key(s[i]):
            dct[s[i]] +=1
        else:
            dct[s[i]]=1
    print dct

    for i in dct:
        if dct[i] == 1:
            position.append(s.index(i))

    position.sort()
    print position
    return s[position[0]]



print repeated("Salesforce is the best company")

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

def repeated(word):
    s = list(word.lower())
    dct={}
    position=[]
    length=len(s)
    for i in range(int(length)):
        if dct.has_key(s[i]):
            dct[s[i]] +=1
        else:
            dct[s[i]]=1
    print dct

    for i in dct:
        if dct[i] == 1:
            position.append(s.index(i))

    position.sort()
    print position
    return s[position[0]]



print repeated("Salesforce is the best company")

- Sathyamoorthy April 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{def repeated(word): s = list(word.lower()) dct={} position=[] length=len(s) for i in range(int(length)): if dct.has_key(s[i]): dct[s[i]] +=1 else: dct[s[i]]=1 print dct for i in dct: if dct[i] == 1: position.append(s.index(i)) position.sort() print position return s[position[0]] {{{print repeated("Salesforce is the best company")}}} - Sathyamoorthy April 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def repeated(word):
s = list(word.lower())
dct={}
position=[]
length=len(s)
for i in range(int(length)):
if dct.has_key(s[i]):
dct[s[i]] +=1
else:
dct[s[i]]=1
print dct
for i in dct:
if dct[i] == 1:
position.append(s.index(i))

position.sort()
print position
return s[position[0]]



print repeated("Salesforce is the best company")

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

char FindNonRepeated(string s) {
		unordered_set<char> dic;
		for(auto x:s)
			dic.insert(x);
		for(auto x:s)
			if(dic.count(x)==0)
				return x;
		return '\0';
	}

- 5F2051EF June 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
     * This method finds the first non repeated character in a given string.Assuming case-insensitive
     *
     * @param string Input string
     * @return Character first non repeated character
     */
    public char getFristNonRepeatedChar(String string){
        //Initialising to default value
        char output = '\u0001';
        //Validating for null and empty string
        if(string == null || string.isEmpty())
            return output;
        //Getting char array form given string
        char [] chars = string.toCharArray();


        HashMap<Character,Integer> countMap = new HashMap<>();
        HashMap<Character,Integer> singleCharMap = new HashMap<>();

        for(char c : chars){
            c = Character.toLowerCase(c);
            //Checking if its an alphabet
            if('a' <= c && c <= 'z'){
                //If it is already present in count map that means its not unique
                if(countMap.containsKey(c)){
                    singleCharMap.remove(c);
                }else{
                    //If its not in count map then insert into count map and single char map
                    countMap.put(c,0);
                    singleCharMap.put(c,0);
                }

            }
        }

        //No entry in single char map
        if(singleCharMap.size()==0)
            return output;

        //iterate on char array and break on first hit
        for(char c : chars){
            if(singleCharMap.containsKey(c)){
                output = c;
                break;
            }
        }

        return output;
    }

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

/**
     * This method finds the first non repeated character in a given string.Assuming case-insensitive
     *
     * @param string Input string
     * @return Character first non repeated character
     */
    public char getFristNonRepeatedChar(String string){
        //Initialising to default value
        char output = '\u0001';
        //Validating for null and empty string
        if(string == null || string.isEmpty())
            return output;
        //Getting char array form given string
        char [] chars = string.toCharArray();


        HashMap<Character,Integer> countMap = new HashMap<>();
        HashMap<Character,Integer> singleCharMap = new HashMap<>();

        for(char c : chars){
            c = Character.toLowerCase(c);
            //Checking if its an alphabet
            if('a' <= c && c <= 'z'){
                //If it is already present in count map that means its not unique
                if(countMap.containsKey(c)){
                    singleCharMap.remove(c);
                }else{
                    //If its not in count map then insert into count map and single char map
                    countMap.put(c,0);
                    singleCharMap.put(c,0);
                }

            }
        }

        //No entry in single char map
        if(singleCharMap.size()==0)
            return output;

        //iterate on char array and break on first hit
        for(char c : chars){
            if(singleCharMap.containsKey(c)){
                output = c;
                break;
            }
        }

        return output;
    }

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

/**
     * This method finds the first non repeated character in a given string.Assuming case-insensitive
     *
     * @param string Input string
     * @return Character first non repeated character
     */
    public char getFristNonRepeatedChar(String string){
        //Initialising to default value
        char output = '\u0001';
        //Validating for null and empty string
        if(string == null || string.isEmpty())
            return output;
        //Getting char array form given string
        char [] chars = string.toCharArray();


        HashMap<Character,Integer> countMap = new HashMap<>();
        HashMap<Character,Integer> singleCharMap = new HashMap<>();

        for(char c : chars){
            c = Character.toLowerCase(c);
            //Checking if its an alphabet
            if('a' <= c && c <= 'z'){
                //If it is already present in count map that means its not unique
                if(countMap.containsKey(c)){
                    singleCharMap.remove(c);
                }else{
                    //If its not in count map then insert into count map and single char map
                    countMap.put(c,0);
                    singleCharMap.put(c,0);
                }

            }
        }

        //No entry in single char map
        if(singleCharMap.size()==0)
            return output;

        //iterate on char array and break on first hit
        for(char c : chars){
            if(singleCharMap.containsKey(c)){
                output = c;
                break;
            }
        }

        return output;
    }

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

/**
* This method finds the first non repeated character in a given string.Assuming case-insensitive
*
* @param string Input string
* @return Character first non repeated character
*/
public char getFristNonRepeatedChar(String string){
//Initialising to default value
char output = '\u0001';
//Validating for null and empty string
if(string == null || string.isEmpty())
return output;
//Getting char array form given string
char [] chars = string.toCharArray();


HashMap<Character,Integer> countMap = new HashMap<>();
HashMap<Character,Integer> singleCharMap = new HashMap<>();

for(char c : chars){
c = Character.toLowerCase(c);
//Checking if its an alphabet
if('a' <= c && c <= 'z'){
//If it is already present in count map that means its not unique
if(countMap.containsKey(c)){
singleCharMap.remove(c);
}else{
//If its not in count map then insert into count map and single char map
countMap.put(c,0);
singleCharMap.put(c,0);
}

}
}

//No entry in single char map
if(singleCharMap.size()==0)
return output;

//iterate on char array and break on first hit
for(char c : chars){
if(singleCharMap.containsKey(c)){
output = c;
break;
}
}

return output;
}

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

ll=list(input())
ss=set()
l=[0]*26
for i in range(len(ll)):
if(ord(ll[i])>=97 and ord(ll[i])<=122):
l[ord(ll[i])-ord('a')]=l[ord(ll[i])-ord('a')]+1vSalesforce is the best company to work for
for k in range(len(l)):
if(l[ord(ll[k])-ord('a')]==1):
print(ll[k])
break

- somesh mahule July 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

There are 3 options to do this :
1) Scan array 1 char at a time and compare with remaining chars. If no duplicate found return, you have just found the first non-repeated char. Time complexity : o(n*n)
2) Sort the array. Scan array by comparing adjacent element. If you find element which is different than its adjacent element, return it. Time complexity : o(n log n) + o(n)
3) Use a hashMap of character and its count. Scan array to populate this map. Finally Scan array and check the count on each char from this hashMap. If it is 1, return that element. Time complexity : o(n) but needs additional o(n) space for hash map.

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

public string FirstNonRepeatedChar(string s)
        {
            char[] schar = s.ToCharArray();
            for(int i=0; i < schar.Length; i++)
            {
                if (s.Substring(i + 1).IndexOf(schar[i]) == -1 && s.Substring(0,i).IndexOf(schar[i]) == -1)
                {                    
                    return schar[i].ToString();
                }
            }
            return null;
        }

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

public string FirstNonRepeatedChar(string s)
        {
            char[] schar = s.ToCharArray();
            for(int i=0; i < schar.Length; i++)
            {
                if (s.Substring(i + 1).IndexOf(schar[i]) == -1 && s.Substring(0,i).IndexOf(schar[i]) == -1)
                {                    
                    return schar[i].ToString();
                }
            }
            return null;
        }

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

use a queue

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

public class FirstNonRepeatingCharacter
{
 
  public static void main(String[] args)
  {
    Queue<Character> charQueue = new LinkedList<Character>();
    String input = "Salesforce is the best company to work for";
    
    Character first = Character.toLowerCase(input.charAt(0));
    charQueue.add(first);
    
    for(int i = 1; i < input.length(); i++){
      Character currentChar = Character.toLowerCase(input.charAt(i));
      if(currentChar.equals(charQueue.peek())){
        charQueue.remove();
      }else{
        charQueue.add(currentChar);
      }
    }
    
    System.out.println(charQueue.remove());
  }
}

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

Use a queue

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

public class FirstNonRepeatingCharacter
{
 
  public static void main(String[] args)
  {
    Queue<Character> charQueue = new LinkedList<Character>();
    String input = "Salesforce is the best company to work for";
    
    Character first = Character.toLowerCase(input.charAt(0));
    charQueue.add(first);
    
    for(int i = 1; i < input.length(); i++){
      Character currentChar = Character.toLowerCase(input.charAt(i));
      if(currentChar.equals(charQueue.peek())){
        charQueue.remove();
      }else{
        charQueue.add(currentChar);
      }
    }
    
    System.out.println(charQueue.remove());
  }

}

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

C# Solution with Dictionary and Linq

public static char FindFirstNonRepeatedCharWithExtraSpace(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return char.MinValue;
            }

            var chars = new Dictionary<char, int>();
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == ' ')
                {
                    continue;
                }
                var key = char.ToLower(input[i]);
                if (chars.ContainsKey(key))
                {
                    chars[key]++;
                }
                else
                {
                    chars.Add(key, 1);
                }
            }
            Console.WriteLine("FindFirstNonRepeatedChar  - " + chars.FirstOrDefault(k => k.Value == 1).Key);
            return chars.FirstOrDefault(k => k.Value == 1).Key;
        }

- .netDecoder June 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {

String s ="satishat";

for(int i =0;i<s.length();i++) {
if(s.indexOf(s.charAt(i))==s.lastIndexOf(s.charAt(i))) {
System.out.println(s.charAt(i));break;
}
}
}

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

public static void main(String[] args) {
		
		String s ="satishat";
		
		for(int i =0;i<s.length();i++) {
			if(s.indexOf(s.charAt(i))==s.lastIndexOf(s.charAt(i))) {
				System.out.println(s.charAt(i));break;
			}
		}

}

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

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

String s ="satishat";

for(int i =0;i<s.length();i++) {
if(s.indexOf(s.charAt(i))==s.lastIndexOf(s.charAt(i))) {
System.out.println(s.charAt(i));break;
}
}
}
}

- Satish September 21, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

#include<string>
#include<set>
#include<iostream>

int main()
{
    std::string input="Salesforce is the best company to work for";
    std::set<char> counter;
    char output;
    for (auto it = std::rbegin(input); it != std::rend(input); ++it)
    {
        char value =  std::tolower(*it);
        if( counter.find(value) == std::end(counter))
        {
            output=value;
            counter.insert(value);
        }
    }
    std::cout << output << "\n";    
}

- steep January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Correct me, if i am wrong. This does not identify anything,neither first nor the last character.

if String = "aabccddeea", your code gives 'e' as the output (neither first, nor last)

- rangacoder January 28, 2016 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

@rangacoder you are wrong, run and check it. I got answer 'b'.

- steep January 28, 2016 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

public void minCharCounter(String word) {
LinkedHashMap<Character, Integer> charcount = new LinkedHashMap<>();
for (int i = 0; i < word.length(); i++) {
if (charcount.get(word.charAt(i)) == null) {
charcount.put(word.charAt(i), 1);
} else {
charcount.put(word.charAt(i), charcount.get(word.charAt(i)) + 1);
}
}

int min = Integer.MAX_VALUE; char min_char = (char) 256;
for (Map.Entry<Character, Integer> count : charcount.entrySet()) {
if(count.getValue() < min) {
min = count.getValue();
min_char = count.getKey();
}
}

System.out.println(min_char + ":" + min);
}

- valdiz777 January 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This gets the min count of characters. If a string is aabbb, then this gives 'a' as the output.
the question is first non-repeated character. this code neither gets first nor the non - repeating one

- rangacoder February 02, 2016 | 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