Amazon Interview Question
Quality Assurance EngineersTeam: Kindle
Country: India
Interview Type: Written Test
public class CharCountString {
public static void main(String[] args) {
System.out.println(findFirstCharMaxKTimes("hello world"));
System.out.println(findFirstCharMaxKTimes("ho lloh"));
}
public static char findFirstCharMaxKTimes(String s) {
int[] charCount = new int[256];
char[] c = s.toCharArray();
int max = 1;
char firstMax = c[0];
int firstIdxOfMax = 0;
charCount[c[0]]++;
for (int i = 1; i < c.length; i++) {
charCount[c[i]]++;
if (charCount[c[i]] >= max) {
int firstIdxChar = s.indexOf(c[i]);
if (charCount[c[i]] > max || (charCount[c[i]] == max && firstIdxChar < firstIdxOfMax)) {
max = charCount[c[i]];
firstMax = c[i];
firstIdxOfMax = firstIdxChar;
}
}
}
return firstMax;
}
}
public char findMostRepeated(String s) {
if(s.length() == 0 ) return ' ';
char[] ch = s.toCharArray();
int[] track = new int[256];
Arrays.fill(track,0);
char out= ' ';
int outCount =0 ;
for(int i =0 ; i < s.length() ; i++){
track[ch[i]]= track[ch[i]] + 1;
if(outCount < track[ch[i]]){
outCount=track[ch[i]];
out = ch[i];
}
}
return out;
}
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String var = " This is a test";
var = var.toLowerCase();
char[] arrVar = var.toCharArray();
Map<Character, Integer> hm = new HashMap<Character, Integer>();
if (!var.isEmpty()){
//loop through characters
for (int i=0;i<arrVar.length;i++){
//check if not space or tab
if (arrVar[i] != ' ' && arrVar[i] != '\t'){
//check if key is already in the hashmap
if (hm.containsKey(arrVar[i])){
hm.put(arrVar[i],hm.get(arrVar[i])+1);
}else{
hm.put(arrVar[i],1);
}
}
}
//check which letter has the highest occurrence
int tempNum = 0;
char tempChar = 'a';
for (Character temp:hm.keySet()){
if (hm.get(temp) > tempNum){
tempNum = hm.get(temp);
tempChar = temp;
}
}
System.out.println(tempChar + " - " + tempNum);
}else{
System.out.println("String is empty");
}
}
}
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String var = " This is a test";
var = var.toLowerCase();
char[] arrVar = var.toCharArray();
Map<Character, Integer> hm = new HashMap<Character, Integer>();
if (!var.isEmpty()){
//loop through characters
for (int i=0;i<arrVar.length;i++){
//check if not space or tab
if (arrVar[i] != ' ' && arrVar[i] != '\t'){
//check if key is already in the hashmap
if (hm.containsKey(arrVar[i])){
hm.put(arrVar[i],hm.get(arrVar[i])+1);
}else{
hm.put(arrVar[i],1);
}
}
}
//check which letter has the highest occurrence
int tempNum = 0;
char tempChar = 'a';
for (Character temp:hm.keySet()){
if (hm.get(temp) > tempNum){
tempNum = hm.get(temp);
tempChar = temp;
}
}
System.out.println(tempChar + " - " + tempNum);
}else{
System.out.println("String is empty");
}
}
}
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String var = " This is a test";
var = var.toLowerCase();
char[] arrVar = var.toCharArray();
Map<Character, Integer> hm = new HashMap<Character, Integer>();
if (!var.isEmpty()){
//loop through characters
for (int i=0;i<arrVar.length;i++){
//check if not space or tab
if (arrVar[i] != ' ' && arrVar[i] != '\t'){
//check if key is already in the hashmap
if (hm.containsKey(arrVar[i])){
hm.put(arrVar[i],hm.get(arrVar[i])+1);
}else{
hm.put(arrVar[i],1);
}
}
}
//check which letter has the highest occurrence
int tempNum = 0;
char tempChar = 'a';
for (Character temp:hm.keySet()){
if (hm.get(temp) > tempNum){
tempNum = hm.get(temp);
tempChar = temp;
}
}
System.out.println(tempChar + " - " + tempNum);
}else{
System.out.println("String is empty");
}
}
}
#include <bits/stdc++.h>
using namespace std;
#define fr(a,b) for(i=a;i<b;i++)
#define rep(a,b) for(i=a;i>=b;i--)
#define f first
#define s second
#define inp(a,n) fr(i,n) cin>>a[i]
#define print(a,n) fr(i,n) {cout << a[i] << " ";} cout << endl
#define ll long long
#define my(type) (char *)(&type+1)-(char *)(&type)
int main()
{
int t;
// cin>>t;
int i;
//while(t--)
{
string s;
cin>>s;
int a[26]={0};
fr(0,s.length())
a[s[i]-'a']++;
int max=INT_MIN;
int index=0;
fr(0,s.length())
{
int x=a[s[i]-'a'];
if(x>max)
{
max=x;
index=i;
}
}
cout<<s[index];
}
}
//Variables used in this program
var str = "Hello World";
var final = [];
var longest = 0, longc = "";
//step 1: Remove whitespace and convert all to similar case
str = str.replace(/\s+/g, "");
var strarr = str.toLowerCase().split("");
//step 2: Call a function to populate the list of all unique characters in this string and their corresponding # of occurrences
for (var i = 0; i < strarr.length; i++) {
populate(strarr[i]);
//alert("Final now is "+final);
}
//step 3: Loop through the final array to find out the character with maximum occurrences
for (var i = 0; i < final.length; i++) {
if (parseInt(final[i][1])>longest){
longest = parseInt(final[i][1]);
longc = final[i][0];}
}
//step 4: Display result
alert("First maximum occurrence for " + longc);
//Function used to populate the array with every unique character and its corresponding number of occurrence from the original string
function populate(c) {
//Assume the character has not occurred in the string so far
var cfound = false;
//loop through the final array to see if this character has already occurred
for (var j = 0; j < final.length; j++)
{
if (c == final[j][0])
{
//if found, set the found variable as true and increment the # of occurence by 1
cfound = true;
final[j][1] = final[j][1] + 1;
}
}
//if found variable is still false after looping through the final array, then push the character to the final array with occurrence initiated as 1, since this is first occurrence
if (cfound == false)
{
final.push([c, 1]);
}
}
//Variables used in this program
var str = "Hello World";
var final = [];
var longest = 0, longc = "";
//step 1: Remove whitespace and convert all to similar case
str = str.replace(/\s+/g, "");
var strarr = str.toLowerCase().split("");
//step 2: Call a function to populate the list of all unique characters in this string and their corresponding # of occurrences
for (var i = 0; i < strarr.length; i++) {
populate(strarr[i]);
//alert("Final now is "+final);
}
//step 3: Loop through the final array to find out the character with maximum occurrences
for (var i = 0; i < final.length; i++) {
if (parseInt(final[i][1])>longest){
longest = parseInt(final[i][1]);
longc = final[i][0];}
}
//step 4: Display result
alert("First maximum occurrence for " + longc);
//Function used to populate the array with every unique character and its corresponding number of occurrence from the original string
function populate(c) {
//Assume the character has not occurred in the string so far
var cfound = false;
//loop through the final array to see if this character has already occurred
for (var j = 0; j < final.length; j++)
{
if (c == final[j][0])
{
//if found, set the found variable as true and increment the # of occurence by 1
cfound = true;
final[j][1] = final[j][1] + 1;
}
}
//if found variable is still false after looping through the final array, then push the character to the final array with occurrence initiated as 1, since this is first occurrence
if (cfound == false)
{
final.push([c, 1]);
}
}
Simple and not too fancy!!
public class CalcMaxChar {
public static void main(String[] args) {
// TODO Auto-generated method stub
String inp = "HO HELLO!";
inp = inp.toLowerCase().trim();
int[] hashArr = new int[26];
int maxIndex = 0;
int maxCount = 0;
for(int i=0; i< inp.length(); i++){
if(inp.charAt(i) >= 'a' && inp.charAt(i) <= 'z') {
int idx = inp.charAt(i)- 'a';
hashArr[idx]++;
if(hashArr[idx] > maxCount){
maxIndex = i;
maxCount = hashArr[idx];
}
}
}
System.out.println(inp.charAt(maxIndex));
}
}
public static boolean findDuplicateChars(String str, boolean ignoreCase){
int i = 0;
if (ignoreCase){
str = str.toLowerCase();
}
boolean isDup = false;
while ((i < str.length()) || (isDup)) {
char s = str.charAt(i);
System.out.println("substring is: " + str.substring(i+1) + "Str val of s is: "+String.valueOf(s) );
if (str.substring(i+1).contains(String.valueOf(s))){
isDup = true;
System.out.println("duplicate character is " + s);
return isDup;
}
i++;
}
System.out.println("No duplicate characters found");
return isDup;
}
public static boolean findDuplicateChars(String str, boolean ignoreCase){
int i = 0;
if (ignoreCase){
str = str.toLowerCase();
}
boolean isDup = false;
while ((i < str.length()) || (isDup)) {
char s = str.charAt(i);
System.out.println("substring is: " + str.substring(i+1) + "Str val of s is: "+String.valueOf(s) );
if (str.substring(i+1).contains(String.valueOf(s))){
isDup = true;
System.out.println("duplicate character is " + s);
return isDup;
}
i++;
}
System.out.println("No duplicate characters found");
return isDup;
}
public static boolean findDuplicateChars(String str, boolean ignoreCase){
int i = 0;
if (ignoreCase){
str = str.toLowerCase();
}
boolean isDup = false;
while ((i < str.length()) || (isDup)) {
char s = str.charAt(i);
System.out.println("substring is: " + str.substring(i+1) + "Str val of s is: "+String.valueOf(s) );
if (str.substring(i+1).contains(String.valueOf(s))){
isDup = true;
System.out.println("duplicate character is " + s);
return isDup;
}
i++;
}
System.out.println("No duplicate characters found");
return isDup;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
findDuplicateChars("hello Hello", false);
}
public static boolean findDuplicateChars(String str, boolean ignoreCase){
int i = 0;
if (ignoreCase){
str = str.toLowerCase();
}
boolean isDup = false;
while ((i < str.length()) || (isDup)) {
char s = str.charAt(i);
System.out.println("substring is: " + str.substring(i+1) + "Str val of s is: "+String.valueOf(s) );
if (str.substring(i+1).contains(String.valueOf(s))){
isDup = true;
System.out.println("duplicate character is " + s);
return isDup;
}
i++;
}
System.out.println("No duplicate characters found");
return isDup;
}
PYTHON::
>>> def max_occ_char(str):
s = str.replace(' ', '')
a = {}
c = ''
for i in s:
if i not in a:
a[i] = 1
else:
a[i] += 1
highest = max(a.values())
for k, v in a.items():
if v == highest:
c = '%s%s'%(c, k)
for j in s:
if j in c:
return j
>>> max_occ_char("LHELOHH WORLD!")
'L'
>>> max_occ_char("HELLOHH WORLD!")
'H'
>>> max_occ_char("HELLO WORLD!")
'L'
>>>
public void getCharThatOccuredMaxTimes(String s){
char[] carr = s.toCharArray();
LinkedHashMap<Character,Integer> lmap = new LinkedHashMap<>();
for(Character c : carr){
if(lmap.containsKey(c)){
lmap.put(c, lmap.get(c)+1);
}
else{
lmap.put(c, 1);
}
}
int max =0;
char ch = 0;
for(Entry<Character, Integer> entry : lmap.entrySet()){
if(max < entry.getValue()){
max = entry.getValue();
ch = entry.getKey();
}
}
System.out.println(ch +""+ max);
}
public static Integer countDuplicateCharacters(String input, char ch) {
int count = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == ch) {
count++;
}
}
return count;
}
public static void printMaxOccuredChar(LinkedHashMap<Character,Integer> lhm) {
int max = 0;
String maxOccured = "";
Set<Character> keys = lhm.keySet();
for(Character ch:keys) {
if(max < lhm.get(ch)) {
max = lhm.get(ch);
maxOccured = "" + ch;
}
}
System.out.println(maxOccured);
}
public static void main(String[] args) {
String str = "HELLO O E";
str = str.replaceAll(" ", "");
LinkedHashMap<Character,Integer> lhm = new LinkedHashMap<>();
for(int i=0; i<str.length(); i++) {
if(!lhm.containsKey(str.charAt(i))) {
lhm.put(str.charAt(i), countDuplicateCharacters(str, str.charAt(i)));
}
}
System.out.println(lhm);
printMaxOccuredChar(lhm);
}
1). Make a linked list with a structure inside:
- sergey.a.kabanov September 18, 2016struct SymbolsAppearance
{
char c;
int iCounter;
}
Going through the string:
if the symbol occurs first time (there is no such "c" in the list yet),
add new element to the list, and make iCounter = 1.
If the symbol already is in the list, increase iCounter for the element with the correspondent "c".
2). Go through linked list and find the first element with maximal "iCounter".