Uber Interview Question
Software EngineersCountry: United States
1. Count the characters of the string (use a map, dictionary or something like that to map from a character to the num of ocurrences in the string)
2. check len of the string
3. If odd, check all characters has odd number of occurrences. If so, return True.
4. If even, check all characters has odd nomber of ocurrences but one. If so, return True.
5. None of 3, or 4, return False
import java.util.HashMap;
public class palindromecanbeformedornotfromgivenstring {
public static void main(String[] args) {
boolean result = false;
String str ="yakak";
HashMap<Character,Integer>hm= new HashMap<Character,Integer>();
int l1=str.length();
char[] c1=str.toCharArray();
for(char c:c1){
if(hm.containsKey(c)){
hm.put(c,hm.get(c)+1);
}
else{
hm.put(c,1);
}
}
if(l1%2==0){
for(char c2 : c1){
int value = hm.get(c2);
if(value%2==0)
result= true;
else
result=false;
}
}
else{
int oddcount=0;
for(char c2 : c1){
int value = hm.get(c2);
if(value%2==0)
continue;
else
oddcount++;
}
if(oddcount<2)
result= true;
else
result=false;
}
if(result==true)
System.out.println("possible");
else
System.out.println("not possible");
}
}
import java.util.Scanner;
public class StringPalindrome {
static int[] visited=null;
static char[] array=null;
static boolean Answer;
public static void Palindrome(int index,char[] temp)
{
if(index>=array.length)
{
int m=0,n=temp.length-1;
boolean b=true;
while(m<n)
{
if(temp[m]!=temp[n])
{b=false;break;}
m++;n--;
}
if(b)
Answer=true;
return;
}
for(int p=0;p<array.length;p++)
{
if(visited[index]==0)
{
visited[index]=1;
temp[index]=array[p];
Palindrome(index+1, temp);
visited[index]=0;
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.next();
array=s.toCharArray();
visited=new int[array.length];
char[] tarray=new char[array.length];
Answer=false;
Palindrome(0, tarray);
System.out.println(Answer);
}
}
import java.util.Scanner;
/**
* Created by dushyant.sabharwal on 11/20/16.
*/
public class PalindromicPermutation {
public static void main(String []args) {
char [] char_map = new char[122];
System.out.println("Enter the string for checking");
Scanner sc = new Scanner(System.in);
String input = sc.next();
sc.close();
boolean even = (0 == input.length() % 2);
for (int i=0; i < input.length(); i++) {
char c = input.charAt(i);
char_map[c]++;
}
int i;
for(i=0; i < char_map.length; i++) {
if (char_map[i] > 0) {
if (even && char_map[i] % 2 != 0) {
System.out.println("No palindrome");
break;
} else if(!even && char_map[i] % 2 != 0) {
even = true;
}
}
}
if (i == char_map.length) {
System.out.println("There is a palindrome");
}
}
}
Your logic is wrong, you switched 3 and 4.
- Shivam Maharshi October 05, 20163. If length is odd then all the characters except one should have even occurrences.
4. If even, then all the characters should have even occurrences.