Interview Question
Country: United States
Interview Type: Written Test
If there is a constraint on space, sort the array and count the consecutive blocks of values. Output the block that is longest. Here is the pseudo code:
SortArray(); <-- O(nlgn)
total=0;
for(i=0;i<n;i++)
{
cnt=1; //there is at least one element i.e., a[i] itself
if(a[i]==a[i+1])
cnt++;
else
{
total+=cnt;
printf("%d is repeated %d times",a[i],cnt);
cnt=0;
}
}
Yes we can use the classes which implement set in java its easy , bit alternative is using the java collections.sort .
1) First split the string and put that to ArrayList
2) sort the arraylist using the collections sort
3) write a business logic to find the duplicates using list[i] == list [i+1]
#################################################################
package com.CareerCup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class DuplicateString implements Comparator<String> {
public static void main(String s[])
{
String str = "this is string of string find is this string ";
String[] splittedString= str.split(" ");
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<String> duplicateList = new ArrayList<String>();
for(String string : splittedString)
{
stringList.add(string);
}
Collections.sort(stringList, new DuplicateString());
int listLen= stringList.size();
for(int i=0;i<listLen-1;i++)
{
if(stringList.get(i).equals(stringList.get(i+1)))
{
duplicateList.add(stringList.get(i));
}
}
System.out.println( duplicateList);
}
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class FindStringCount {
Hashtable resultHash = new Hashtable();
public static void main(String[] args) {
// TODO Auto-generated method stub
int dups = 0;
String sentence = "string this is a string for a string"; // Some value here
Set<String> set = new HashSet<String>();
for (String w : sentence.split("\\s+")) {
//System.out.println(w);
if (!set.add(w)) dups++;
}
System.out.println(set);
FindStringCount searchCount = new FindStringCount();
Iterator ite = set.iterator();
while(ite.hasNext()){
searchCount.process(sentence, ite.next());
}
System.out.println(searchCount.resultHash);
//searchCount.process(sentence, searchChar);
}
private void process(String sentence, Object searchChar){
int count = 0;
for (String w : sentence.split("\\s+")) {
if(searchChar.equals(w)) count++;
}
if(count >0 ) {
resultHash.put(searchChar, count);
}
}
}
- avl July 17, 2013